> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sketricgen.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Orchestration & Handoffs

> Multi-agent orchestration in SketricGen — AI-routed handoffs, forced handoffs for sequential pipelines, and Agent-as-a-Tool for modular sub-tasks.

## Overview

Orchestration in SketricGen defines **how agents collaborate** inside a workflow.

Each agent operates semi-independently but follows your defined logic to decide **when** to hand off control or call another agent as a tool.

SketricGen supports both **AI-routed orchestration** (where the model decides the next step) and **designer-routed orchestration** (where you manually connect agents with explicit edges in the AgentSpace).

***

## How Routing Works (AI-Routed)

In **AI-routed orchestration**, agents decide when to hand off based on their **instructions** and **current input**, rather than following a fixed sequence.

This routing style gives agents autonomy to decide:

* Whether to continue reasoning, call a tool, or pass control to another agent.
* Which downstream agent is most appropriate for the current intent.

To achieve reliable AI-routed behavior:

* Designate a clear **entry agent** (such as "Manager" or "Triage") to handle all first messages.
* Write **precise conditions** in the agent's instructions describing when to hand off and when to handle the query directly.
* Keep roles distinct — avoid overlapping functions between agents.

***

## Handoff vs Agent-as-Tool

### Handoff (Agent → Agent)

A **handoff** transfers full control from one agent to another.

Once handed off, the target agent owns the next reasoning turn and may further hand off to others.

This way, if the input message intent is completed, the Agent in control returns the final response. So there is no fixed start and endpoint in the AgentSpace unlike most Automations.

**Characteristics**

* Passes control of the Run permanently until another handoff occurs.
* Maintains continuity of context (structured inputs can be passed).
* Ideal for sequential or role-based pipelines (e.g., triage → specialist → responder).

### Agent-as-Tool

In this setup, an agent acts as a **callable utility** rather than a control-transfer node.

The parent agent calls it as a sub-routine, waits for it to complete, and resumes control when the result is returned.

Common use cases:

* Text classification
* Information extraction
* Summarization or redaction tasks

**Control-flow rule of thumb:**

Once handed off, a child won't automatically return control to the parent unless you define a *handoff back*.

If the parent should remain in charge, model the secondary logic as **Agent-as-Tool** instead.

**Important:**

The agent directly connected to the **Trigger node** cannot be configured or used as an Agent-as-Tool.

***

## Forced Handoff (Designer-Routed)

While **AI-routed orchestration** gives agents autonomy to decide when to hand off, **Forced Handoff** provides **deterministic, designer-controlled routing** that guarantees an agent will pass control to a specific target agent after completing its task — regardless of what the AI decides.

### When to Use Forced Handoffs

Use forced handoffs when you need:

* **Guaranteed execution flow**: Ensure Agent B always runs after Agent A completes.
* **Pipeline-style workflows**: Sequential processing where each agent must run in order (e.g., Research → Draft → Review → Publish).
* **Compliance or audit requirements**: When every step must be executed and logged.
* **Fallback assurance**: When the AI might not naturally hand off but you need downstream processing.

### How Forced Handoff Works

1. **Edge Configuration**: Mark an edge between two agents as a "Forced Handoff" on the AgentSpace.

2. **Natural Handoff Skipping**: When an edge is marked as forced, the system skips creating a natural handoff for that same connection. This prevents duplicate routing logic.

3. **Orchestrator Execution**: The `ForcedHandoffOrchestrator` manages the execution:
   * Executes the source agent to completion
   * Automatically transfers control to the target agent
   * Transforms output into input for the next agent
   * Maintains a unified trace across all hops

4. **Context Preservation**: Conversation history and agent outputs are transformed and passed to the next agent, maintaining continuity.

### Forced Handoff vs Natural Handoff

| Aspect               | Natural Handoff (AI-Routed)             | Forced Handoff (Designer-Routed)           |
| -------------------- | --------------------------------------- | ------------------------------------------ |
| **Decision Maker**   | AI model decides based on instructions  | Designer configures; always executes       |
| **Predictability**   | Variable — depends on input and context | Deterministic — guaranteed execution path  |
| **Use Case**         | Flexible, intent-based routing          | Sequential pipelines, compliance workflows |
| **Control Transfer** | May or may not occur                    | Always occurs after source agent completes |

### Safety Mechanisms

* **Maximum Hop Limit**: Default limit of 10 agent transitions prevents infinite loops.
* **Execution Tracking**: Each agent's execution count is tracked to prevent runaway chains.
* **Unified Tracing**: All agent transitions appear in a single trace for debugging.

### Best Practices for Forced Handoffs

* Use forced handoffs for **critical paths** where every step must execute.
* Combine with **Structured Inputs/Outputs** to ensure clean data passing between agents.
* Keep forced chains **short and linear** — complex branching is better suited for AI-routed orchestration.
* Review traces to verify the orchestrator is correctly transforming outputs between hops.

### When NOT to Use Forced Handoffs

* When routing should be **intent-dependent** (use AI-routed instead).
* For **optional processing paths** where downstream agents may not be needed.
* When agents need to **decide** between multiple downstream options based on context.

***

## Writing Effective Instructions

To orchestrate reliably:

* Define each agent's **role**, **goal**, and **handoff criteria** in its instructions.
* Provide clear logic for **when to use tools** and **when to delegate**.
* Treat your entry agent as the **gateway** for all new inputs.

Example guidance line:

> "If the query requires data retrieval or document lookup, hand off to Responder; otherwise, respond directly."

***

## Structuring Data Between Agents

Data flow in orchestration depends on **Structured Inputs and Outputs**.

* Use **Structured Inputs** on child agents so the parent knows exactly what to supply before a handoff.
* Use **Structured Outputs (JSON)** on final responder agents to ensure consistent output or API responses.
* Define only necessary fields; keep schemas concise.

Example:

```json theme={null}
{
  "intent": "string",
  "customer_id": "integer",
}
```

***

***

## Starter Patterns (AI-Routed)

These are common multi-agent orchestration setups you can replicate or adapt:

| Pattern                                            | Description                                                                          |
| -------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Manager → Researcher → Writer                      | Manager routes research tasks, Researcher compiles info, Writer drafts the response. |
| Manager → (Agent-as-Tool: Classifier) → Specialist | Classifier determines type; Specialist handles it further.                           |
| Manager → Specialist → (Agent-as-Tool: Summarizer) | Specialist processes and sends text to Summarizer for concise output.                |

***

## Best Practices

* Always define one clear **entry agent** to receive initial inputs.
* Use **handoffs** for ownership transfer and **Agent-as-Tool** for short, reusable subtasks.
* Keep handoff paths labeled and intentional.
* Use **forced handoffs** for critical, sequential pipelines where every step must execute — reserve AI-routed handoffs for intent-based flexibility.
* Validate Structured Inputs and Outputs to prevent schema mismatches.
* Review traces after each major workflow run to fine-tune orchestration.
* Keep logic simple and modular — complexity should emerge from clarity, not layers.
