Agentic Orchestration Foundations
Building robust autonomous systems with Claude requires a deterministic control loop managed by the host application. Unlike simple prompt-completion request cycles, an agentic loop iteratively executes tool calls until a terminal condition is satisfied.
The Turn Cycle & Stop Reasons
When invoking Claude with tools configured, the orchestrator inspects the response's `stop_reason` to decide the next action:
- **`tool_use`**: The model decided that completing the user request requires one or more external tool executions. The response contains a `content` array with tool use blocks specifying `id`, `name`, and `input`.
- **`end_turn`**: The model completed its answer and requires no further tool execution. The agent loop should terminate and return the output.
- **`max_tokens`**: Generation stopped prematurely due to token budget depletion. The orchestrator must handle this gracefully, either prompting for continuation or alerting the caller.
while (turnCount < MAX_TURNS) {if (response.stop_reason === "end_turn") { return extractTextOutput(response); }
if (response.stop_reason === "tool_use") { const toolResults = await executeTools(response.content); params.messages.push({ role: "assistant", content: response.content }); params.messages.push({ role: "user", content: toolResults }); turnCount++; continue; }
throw new Error(`Unexpected stop reason: ${response.stop_reason}`); } ```
Supervisor-Subagent Delegation
For complex workflows, a single flat conversation history degrades as token count climbs. A superior architecture is the **Supervisor-Subagent pattern**: - The **Supervisor** plans the task and decomposes it into isolated sub-goals. - Dedicated **Subagents** receive focused prompts, execute domain tools, and return succinct summaries back to the supervisor. - This bounds context usage, prevents distraction, and enables parallel execution paths.