Core Concepts
Architecture Overview
Agent SDK is built on LangGraph and provides a complete agent execution framework with nodes, state management, and streaming support.
Agent Execution Flow
User Query
↓
SenseNode (Session validation, intent classification, tool discovery)
↓
SummarizationNode (Compress history if context window is filling — conditional)
↓
ReasonNode (Analyze request, plan approach, LLM interaction)
↓
ToolNode (Execute MCP tools) OR ResponseNode (Format response)
│ │
├─ AgentExecutorNode │
│ (DAG/wavefront execution │
│ for multi-step plans) │
│ ↓ │
│ ToolNode (loop) │
↓ ↓ ↓
GuardrailNode (Safety checks, compliance — optional)
↓
FailsafeNode (Error recovery — on failure)
↓
ResultCore Components
1. Agent State
The AgentState is a TypedDict that flows through the graph:
class AgentState(TypedDict):
messages: List[BaseMessage] # Conversation history
session_id: str # Session identifier
shared_state: Dict[str, Any] # Mutable shared data
task_list: List[Dict] # Flat task list
task_dag: Optional[DAGState] # DAG task structure
current_task_index: int # Current task in flat list
confidence: float # Response confidence score
# ... and moreState fields use annotated reducers for merging:
preserve_latest- Keep the most recent valueadd_messages- Append to message listsum_numeric- Add numeric valuesmerge_dicts- Deep merge dictionaries
2. Nodes
Nodes are the building blocks of agent execution:
SenseNode (Entry)
- Validates session existence or creates new sessions
- Classifies intent (simple vs. complex)
- Discovers available tools and skills
- Prepares enhanced system prompt
- Handles event-driven triggers in proactive mode
ReasonNode
- Analyzes the current request and plans the approach
- Handles LLM interactions via
ModelCallingMixin - Manages streaming responses and token billing
- Determines if tools are needed and routes to next node
- Detects sensitive requests for human-in-the-loop
ToolNode
- Executes tool calls provided by MCP servers (e.g. Read, Write, Edit, Bash from isA_MCP)
- Manages MCP tool discovery and invocation
- Handles autonomous task planning
- Detects and builds DAG structures from task lists
ResponseNode
- Formats final responses
- Applies output format schemas
- Handles structured outputs
- Validates response structure
GuardrailNode
- Applies safety guardrails
- Checks for PII and sensitive data
- Enforces compliance rules (HIPAA, etc.)
- Sanitizes or blocks responses based on violations
SummarizationNode
- Compresses conversation history when context window fills using the official LangGraph
RemoveMessagepattern - Preserves the last N messages (default: 5) in full, summarizes older messages via LLM
- Uses a fast/cheap model (default:
gpt-4o-mini) for summary generation - Token-aware compression with estimated savings logging
- Graceful fallback — if summarization fails, the conversation continues unchanged
- Use the
should_summarizehelper as a conditional edge to trigger based on message count thresholds
from agent_sdk.nodes import SummarizationNode
node = SummarizationNode(preserve_last_n=5, summary_model="gpt-4o-mini")AgentExecutorNode
- Coordinates multi-step task execution across flat lists and DAG-based dependency graphs
- When
task_dagis present in state, usesDAGSchedulerto compute wavefronts via Kahn’s algorithm and executes each wavefront in parallel - When only
task_listis present, iterates tasks sequentially usingcurrent_task_index - Cascades failures to dependent tasks (marks downstream as SKIPPED)
- Integrates with SwarmOrchestrator for multi-agent DAG execution where different agents handle different tasks
FailsafeNode
- Handles errors gracefully
- Categorizes error types (UNCERTAINTY, INSUFFICIENT_INFO, etc.)
- Provides context-aware fallback responses
- Ensures transparent failure communication
3. Execution Modes
The SDK supports three execution modes:
Reactive (Default)
- Responds to explicit requests only
- No proactive suggestions
- Straightforward request-response pattern
Collaborative
- Creates checkpoints for human approval
- Requests permission for sensitive operations
- Interactive workflow with user involvement
- Durable execution with state persistence
Proactive
- Anticipates user needs
- Suggests next actions
- More autonomous behavior
- Still respects tool permissions
4. Streaming
All agent operations support streaming:
async for msg in query("Hello"):
if msg.is_text:
print(msg.content, end="")
elif msg.is_tool_use:
print(f"\n[Using {msg.tool_name}]")
elif msg.is_tool_result:
print(f"[Result: {msg.content[:50]}...]")Message types:
is_text- Text contentis_tool_use- Tool invocationis_tool_result- Tool execution resultis_error- Error messageis_result- Final result (for structured outputs)
5. Multi-Agent Systems
MultiAgentOrchestrator
Fixed routing with explicit router function:
def router(state, last_result):
outputs = state.get("outputs", {})
if "planner" not in outputs:
return "planner"
if "renderer" not in outputs:
return "renderer"
return NoneBest for: Known routing patterns, sequential workflows.
SwarmOrchestrator
Dynamic routing with LLM-directed handoffs:
swarm = SwarmOrchestrator(
agents=[researcher, writer],
entry_agent="researcher",
max_handoffs=5,
)Agents decide when to hand off via [HANDOFF: agent_name] directives.
Best for: Dynamic workflows, specialist agents, collaborative tasks.
6. DAG Task Execution
Tasks with dependencies execute in wavefronts:
tasks = [
{"id": "a", "title": "Task A"},
{"id": "b", "title": "Task B", "depends_on": ["a"]},
{"id": "c", "title": "Task C", "depends_on": ["a"]},
{"id": "d", "title": "Task D", "depends_on": ["b", "c"]},
]Execution order:
Wavefront 0: [a] # No dependencies
Wavefront 1: [b, c] # Depend on a (parallel)
Wavefront 2: [d] # Depends on b and cFeatures:
- Cycle detection - Kahn’s algorithm validates DAG structure
- Failure cascade - Failed tasks mark dependents as SKIPPED
- Multi-agent - Different agents execute different tasks in parallel
- Status tracking - PENDING → READY → RUNNING → COMPLETED/FAILED/SKIPPED
7. Options Configuration
AgentOptions controls agent behavior:
options = AgentOptions(
allowed_tools=["Read", "Edit", "Bash"],
execution_mode="collaborative",
max_iterations=20,
confidence_threshold=0.7,
system_prompt="You are a helpful assistant.",
skills=["documentation", "code-review"],
output_format=OutputFormat.from_pydantic(MySchema),
)Key options:
allowed_tools- Tool whitelistexecution_mode- reactive/collaborative/proactivemax_iterations- Maximum graph iterations (must be > 0)confidence_threshold- Minimum confidence for responses (0.0-1.0)system_prompt- System prompt or SystemPromptConfigskills- Skills to loadoutput_format- Structured output schema
8. Human-in-the-Loop
Request permission before dangerous operations:
authorized = await request_tool_permission(
"delete_file",
{"path": "important_data.txt"}
)Create checkpoints for durable execution:
await checkpoint("before_deployment", {
"version": "2.0.0",
"environment": "production"
})9. Sessions and Memory
Sessions maintain conversation context:
# Create session
session = await create_session(user_id="user123")
# Query with session
async for msg in query(
"What did we discuss earlier?",
options=AgentOptions(session_id=session.id)
):
print(msg.content)Sessions store:
- Conversation history
- Shared state
- Checkpoints
- Task progress
10. Tools
Important: The SDK provides the tool execution framework only — it contains no built-in tools. All tools are provided externally by MCP (Model Context Protocol) servers. The primary tool server is isA_MCP, which exposes 190+ tools over the MCP transport.
Common tools available via MCP servers:
- Read - Read files
- Write - Create/overwrite files
- Edit - Edit specific file sections
- Bash - Execute shell commands
- WebSearch - Search the web
- WebFetch - Fetch web content
- Glob - Find files by pattern
- Grep - Search file contents
Custom tools can be defined in-process using the @tool decorator or by connecting additional MCP servers.
11. Skills
Skills are reusable agent capabilities defined in markdown:
.aix/skills/my-skill/SKILL.mdSkills are loaded:
- First from
.aix/skills/(local, project-specific) - Then from MCP servers (shared, global)
This allows project-specific overrides of global skills.
Data Flow
Query Execution
query(prompt, options)
→ SmartAgentGraphBuilder.build()
→ Graph execution with streaming
→ AgentMessage stream
→ User receives responsesSwarm Execution
swarm.run(prompt)
→ Entry agent runs with handoff prompt injection
→ Parse response for [HANDOFF:] or [COMPLETE]
→ If handoff: switch agent, inject context
→ If complete: return SwarmRunResult
→ Max handoffs safety capDAG Execution
swarm.run_dag(tasks)
→ DAGScheduler.build_dag(tasks)
→ DAGScheduler.validate(dag)
→ DAGScheduler.compute_wavefronts(dag)
→ For each wavefront:
→ Run all tasks in parallel (per agent)
→ Aggregate results
→ Pass to dependent tasks
→ Return SwarmRunResult with agent_outputsWorkflows-First Architecture & Two-Tier Model
Following Anthropic’s Building Effective Agents guidance, the platform establishes a Two-Tier Orchestration Model that prioritizes deterministic workflows before escalating to dynamic swarms:
| Tier | Engine | Execution Domain | Latency | Role |
|---|---|---|---|---|
| Tier-1 (Micro) | isA_Agent_SDK | In-process, streaming | < 1s – 5s | Implements 5 canonical patterns: Augmented LLM, Chain, Route, Parallel, and Evaluator-Optimizer. Enforces per-step tool isolation (tool_choice="none" when tools=[]). |
| Tier-2 (Macro) | isa_maestro | Distributed (FastAPI, Redis, Postgres) | Minutes to days | Orchestrates enterprise APQC PCF compliance, RPA bot queues, cross-engine jobs, and Action Center (HITL). Wraps micro-workflows in strict SLA envelopes. |
Progressive Escalation Ladder
single (augmented LLM) ──► workflow (deterministic) ──► subagents ──► dynamic_team (swarm)- single: Direct single-turn completion for simple queries.
- workflow: Deterministic sequential or parallel execution (Chain, Route, Parallel, Evaluator-Optimizer) for 80% of multi-step tasks.
- subagents: Parallel workers for independent sub-tasks.
- dynamic_team: Open-ended multi-agent research swarms with dynamic handoffs.
Knowledge Graph & Lineage Contracts
When agents read from or write to the enterprise data fabric, execution state and produced assets are grounded in the platform’s unified graph schema:
Canonical :Run and :DataAsset Graph Projection
All execution runs and digital artifacts are canonically projected into the platform graph plane:
:Run: Execution nodes (run:<uuid>) capturing task identity, lifecycle status, timing, and OpenTelemetry trace contexts.:DataAsset: Artifact nodes (data_asset:<uuid>) representing datasets, tables, models, or files.- Lineage Edges: Connected via
(:DataAsset)-[:PRODUCED_BY]->(:Run),(:DataAsset)-[:CONSUMED_BY]->(:Run), and(:Run)-[:CAUSED_BY]->(:Run).
Shape Admittance Validation
To safeguard against hallucinated relationships and ungrounded entities, writes to the graph plane must satisfy the ShapeAdmittanceValidator. Triples are checked against closed-vocabulary edge shapes (ONTOLOGY_EDGE_SHAPES) and natural key formats (prefix:key), preventing semantic drift.
For full architectural details, see the Visual Ontology Studio & Shape Admittance specification.
Best Practices
- Default to Workflows First - Use deterministic workflows (
Workflow.chain,Workflow.route,Workflow.evaluator_optimizer) for predictable multi-step tasks before escalating to swarms. - Enforce Scoped Tool Isolation - Only inject tools needed for that specific stage. Passing
tools=[]enforcestool_choice="none", preventing hallucinations and context bloat. - Decouple the Evaluator in Refinement Loops - Use a functionally separated judge prompt (and cheaper model) with a hard
max_revisionscap to eliminate infinite loops. - Channel-Aware Budgets - Enforce strict SLA and token budgets for latency-sensitive channels (Mobile/IM: 30s / 4k tokens).
- Use Collaborative Mode for Risky Operations - Get human approval via checkpoints before destructive actions.
- Use Structured Outputs for Data - Type-safe validation with Pydantic schemas.
- Handle Errors Gracefully - Handle
msg.is_errorand gate rejections (workflow.gate.reject). - Test with Comprehensive Coverage - Maintain regression suites across feature coverage, boundary conditions, and cross-service integration.
Next Steps
- Workflows - Fluent workflow builders and the 5 canonical patterns
- Configuration - Detailed configuration guide
- Multi-Agent - Multi-agent orchestration patterns
- Swarm - Swarm orchestration and DAG execution
- Examples - Practical code examples
- API Reference - Complete API documentation