Skip to main content

Graph System

The SpoonOS Graph System is a powerful library for building stateful, multi-step AI agent workflows. It models applications as directed graphs where nodes represent actions (calling an LLM, executing a tool, processing data) and edges define how control flows between themβ€”including conditional branching, parallel fan-out, and cycles for iterative reasoning.

Start Here​

  • Just getting started? Go straight to Quick Start for a runnable example in under 2 minutes.
  • Want to understand the building blocks? Read Core Concepts after the quick start.
  • Need API styles and patterns? See Building Graphs and Examples.
  • Looking for routing/parallel/HITL quick snippets? Jump to Advanced Features
  • Need setup? Follow Getting Started / Installation before running examples.
  • You will learn: How to build, run, and checkpoint simple graphs
  • Best for: First-time users; time to complete: 2–5 minutes

Common Pitfalls​

  • Checkpoint APIs (get_state, get_state_history) require a thread_id in config.configurable
  • Use the exported constants (from spoon_ai.graph import END) instead of string literals
  • When adding parallel groups, ensure all member nodes are registered before grouping
  • Conditional routes must return existing node names (or END) to avoid configuration errors

What is the Graph System?​

Think of the Graph System as a workflow orchestration engine for AI agents. Instead of writing linear chains of prompts and responses, you define a graph where each node is a specific task, and edges determine the flow between tasks based on data, conditions, or even LLM decisions.

This simple graph shows how a single user query can be routed to different processing paths based on detected intent, with results flowing to appropriate next steps.

Why Use Graphs for Agents?​

Traditional LLM applications are often simple chains: prompt β†’ response β†’ done. But real-world AI agents need more sophisticated capabilities:

Core Capabilities​

CapabilityDescriptionUse Case
State PersistenceRemember context across multiple steps and interactionsMulti-turn conversations, data accumulation
Conditional LogicTake different paths based on LLM outputs or external dataIntent routing, quality checks
Parallel ExecutionRun multiple tasks simultaneously and combine resultsMulti-source data fetching, redundancy
Human-in-the-LoopPause for user input, approval, or correctionTrade confirmations, content review
Error RecoveryHandle failures gracefully without losing progressRetry with backoff, circuit breakers
Iterative RefinementLoop back to improve results based on validationQuality improvement, self-correction

Real-World Scenarios​

Autonomous Research Agent: Search β†’ Grade relevance β†’ Regenerate query if needed β†’ Synthesize findings

  • Without graphs: Hard-coded retry logic, tangled control flow
  • With graphs: Clean conditional edges, checkpointed state for recovery

Multi-Source Data Analysis: Fetch from APIs A, B, C in parallel β†’ Wait for quorum β†’ Aggregate β†’ Generate report

  • Without graphs: Manual thread management, complex error handling
  • With graphs: Built-in parallel execution with join strategies and timeouts

Trading Assistant: Analyze market β†’ Generate recommendation β†’ Human approval β†’ Execute trade β†’ Confirm

  • Without graphs: Interrupt/resume logic scattered across codebase
  • With graphs: First-class interrupt nodes with stateful resumption

Graph System vs LangGraph​

SpoonOS Graph System is inspired by LangGraph and shares similar concepts. Here's how they compare:

FeatureSpoonOS GraphLangGraph
Core ParadigmStateGraph with typed state dictionaryStateGraph with message passing
Parallel GroupsNative add_parallel_group() with quorum joins, timeouts, circuit breakersManual asyncio or branching
Routing StackPriority-based: explicit β†’ rules β†’ intelligent β†’ LLM β†’ fallbackConditional edges only
Declarative DefinitionGraphTemplate / NodeSpec / EdgeSpec for serializable, composable graphsImperative builder only
Resource ControlBuilt-in rate limiting, max concurrency, circuit breakersExternal implementation
Web3/CryptoNative integration with SpoonOS toolkits (CEX, DEX, on-chain)Via third-party tools
High-Level APIAutomatic parameter inference from LLM analysisManual parameter extraction

When to choose SpoonOS Graph:

  • βœ… Need production-grade parallel execution with sophisticated join strategies
  • βœ… Require multi-layer routing (rules β†’ intelligent β†’ LLM fallback)
  • βœ… Building crypto/DeFi/Web3 agents with native blockchain integration
  • βœ… Want declarative graph templates for version control and team collaboration
  • βœ… Need automatic parameter inference from natural language queries

When to consider LangGraph:

  • LangChain ecosystem integration is primary requirement
  • Simpler message-passing paradigm fits your use case
  • Want to leverage LangSmith for tracing and debugging

When to Use Graph vs ReAct Agents​

Decision FactorUse Graph SystemUse ReAct Agent
Workflow ComplexityMulti-step, branching, or parallel workflowsSingle-shot or simple tool-calling
State ManagementNeed to persist state across multiple stepsStateless or simple context
Control FlowConditional routing, loops, human-in-the-loopLinear execution with tool calls
ScalabilityMultiple concurrent operations, resource limitsSimple, fast responses
Error HandlingSophisticated retry, recovery, circuit breakersBasic error messages
Use Case ExamplesResearch pipelines, trading systems, multi-agent collaborationQ&A, simple task execution, one-shot analysis

Rule of Thumb: If you need more than 3 sequential steps OR any kind of branching/parallel execution OR state that persists across interactions β†’ use Graph System.

What Can You Build?​

Autonomous Agents​

Multi-step reasoning with tool calls, observation loops, and adaptive planning. Example: Research agent that searches β†’ evaluates source quality β†’ decides to search again or synthesize.

RAG Pipelines​

Retrieve β†’ Grade β†’ Regenerate cycles with conditional routing based on relevance scores. Example: Keep searching until you find high-quality sources or hit iteration limit.

Multi-Agent Systems​

Multiple specialized agents collaborating via shared state and handoffs. Example: Analyst agent β†’ Risk agent β†’ Execution agent with approval gates.

Trading Workflows​

Market analysis β†’ Strategy generation β†’ Human approval β†’ Order execution β†’ Monitoring. Example: Crypto trading assistant with human-in-the-loop for all trades.

Parallel Analysis​

Fan-out to multiple data sources, join results with configurable strategies. Example: Fetch price data from 5 exchanges, use quorum (3/5) for consensus.

Architecture at a Glance​

Three phases:

  1. Build: Define your workflow topology (nodes, edges, routing)
  2. Compile: Create executable runtime with optimizations
  3. Execute: Run the workflow with invoke() or stream()

Throughout execution, a shared state (TypedDict) flows through the graph, with each node reading and updating relevant fields.

Next Steps​

Ready to build your first graph? Start with the Quick Start Guide to see a working example in under 2 minutes.

Or dive deeper into Core Concepts to understand the building blocks: State, Nodes, Edges, and Checkpointing.


Quick Links:

External Resources: