SpoonAI SDK and SpoonOS Core Developer Framework

repository·main·Indexed 42 days ago

https://github.com/xspoonai/spoon-core

An agentic operating system and SDK (version 0.4.10) for building sentient, composable, and interoperable AI agents. It features a strong focus on Web3, MCP-driven tool ecosystems, and trustless AI agent identity via ERC-8004, NeoX blockchain, and NeoFS decentralized storage. The framework includes support for Model Context Protocol (MCP) tool calling, secure signing and wallet management via Turnkey, and specialized agent demos for crypto analysis and memory management.

Tokens
24.8K
Snippets
80
Records
100
Agent score
53%

What's inside SpoonAI

  1. Overview of SpoonOS Core Developer Framework (SCDF)

    main

    SpoonOS Core Developer Framework (SCDF) is an agentic operating system designed for the sentient economy, specifically optimized for Web3 developers. It provides a toolkit for building sentient, composable, and interoperable AI agents.

    Key capabilities include:

    • ReAct Intelligent Agents: Reasoning and action-based architecture.
    • Multi-Model Support: Integration with OpenAI, Anthropic, DeepSeek, and Web3-tuned LLMs.
    • MCP (Model Context Protocol): Dynamic tool invocation via stdio, http, or websocket without restarts.
    • Web3-Native Interoperability: Agent coordination via DID and ZKML-powered protocols.
    • Enhanced Graph System: Workflow orchestration with state management and human-in-the-loop patterns.
    • x402 Payment Rails: Native support for paywalled agent actions via a FastAPI gateway and facilitator client.
  2. Overview of the spoon-core project structure

    main

    The project is organized into several key directories:

    • spoon_ai/: The core framework containing agents/, tools/, llm/, graph.py, and chat.py.
    • examples/: Ready-to-run demos for agents, MCP, and graphs.
    • doc/: Comprehensive documentation for configuration, agents, graphs, MCP, and the CLI.
    • main.py: The primary CLI entry point.
    • config.json: The auto-generated runtime configuration file.
  3. Use Web3 tools via MCP (Model Context Protocol)

    main

    SpoonOS supports runtime pluggable agents using the Model Context Protocol (MCP). This allows agents to connect to live tool servers (via SSE, WebSocket, or HTTP) to access tools like get_contract_events or get_wallet_activity without writing custom tool code.

    There are two primary modes:

    1. Built-in Agent Mode: Build and run your own MCP server and connect to it using an MCPClientMixin agent.
    2. Community Agent Mode: Use mcp-proxy to connect to open-source agents hosted on GitHub.
  4. Apply the Web3 Research Analysis Framework

    main

    When performing research using this skill, the system follows a structured six-step framework to ensure comprehensive coverage:

    1. Market Overview: Current price, market cap, trading volume, and sentiment.
    2. Technology Analysis: Protocol architecture, consensus mechanisms, and scalability.
    3. Tokenomics Review: Supply, distribution, utility, and inflation/deflation mechanics.
    4. Ecosystem Assessment: DApps, partnerships, developer activity, and community health.
    5. Risk Analysis: Security, regulatory, competition, and centralization risks.
    6. Investment Thesis: Bull case, bear case, catalysts, and price targets.
  5. Select an Analysis Type for Web3 research

    main

    The Web3 Research Skill supports three specialized modes of analysis depending on your requirements:

    • Fundamental Analysis: Focuses on team track records, technology roadmaps, token utility, competitive positioning, and revenue models.
    • Technical Analysis: Focuses on price action, chart patterns, support/resistance levels, volume trends, and on-chain metrics (e.g., TVL, active addresses).
    • Sentiment Analysis: Focuses on social media trends, developer activity (GitHub), whale movements, and news coverage.
  6. Build Workflows with the Graph System

    main

    The StateGraph architecture allows you to build complex, stateful AI workflows using nodes, edges, and conditional routing. It supports multi-agent coordination, human-in-the-loop interruptions, and state persistence via checkpointing.

    from spoon_ai.graph import StateGraph
    from typing import TypedDict
    
    class WorkflowState(TypedDict):
        counter: int
        completed: bool
    
    def increment(state: WorkflowState):
        return {"counter": state["counter"] + 1}
    
    def complete(state: WorkflowState):
        return {"completed": True}
    
    # Build and execute workflow
    graph = StateGraph(WorkflowState)
    graph.add_node("increment", increment)
    graph.add_node("complete", complete)
    graph.add_edge("increment", "complete")
    graph.set_entry_point("increment")
    
    compiled = graph.compile()
    result = await compiled.invoke({"counter": 0, "completed": False})
    # Result: {"counter": 1, "completed": True}
  7. How the ERC-8004 DID Agent Architecture works

    main

    The ERC-8004 demo implements a trustless AI agent identity using three main pillars:

    1. Identity Registry (NeoX Testnet): Stores the tokenURI which points to the agent's metadata.
    2. Decentralized Storage (NeoFS): Hosts the actual Agent Card (JSON metadata) and DID Document (W3C standard).
    3. Agent Server: A ReAct-style agent (ERC8004SearchAgent) that uses tools like Tavily for web search to answer questions.

    Workflow: The Client Agent fetches metadata from the on-chain Identity Registry, resolves the NeoFS URIs to get the Agent Card and DID, and then sends queries to the Server Agent via a POST request to the /ask endpoint.

  8. Setup Turnkey Examples environment

    main

    To run the Turnkey SDK sample workflows, you must configure your environment with Turnkey credentials and optional Web3 parameters.

    1. Install Dependencies: Ensure you have Python 3.12+ and install the project dependencies from the root:

      pip install -e .
      # If missing, install extra dependencies:
      pip install web3 rlp eth-utils
    2. Configure Environment Variables: Copy the example environment file and populate it with your credentials:

      cp examples/turnkey/env.example .env

    Required Variables:

    • TURNKEY_API_PUBLIC_KEY
    • TURNKEY_API_PRIVATE_KEY
    • TURNKEY_ORG_ID
    • TURNKEY_SIGN_WITH (The identity used for signing)

    Optional Variables:

    • WEB3_RPC_URL: Your network RPC endpoint (e.g., Sepolia, Mainnet) for broadcasting transactions.
    • TURNKEY_UNSIGNED_TX_HEX: A pre-built unsigned transaction hex used in the trading demo.
    cp examples/turnkey/env.example .env
  9. Use OpenViking as Agent Memory Middleware

    main

    OpenViking can be attached as middleware to SpoonReactAI to provide long-term context. It recalls context before an agent run and commits messages/tool activity after the run. It does not replace SpoonOS graph state or Mem0.

    Setup

    Install the optional dependency:

    pip install -e '.[openviking]'

    Set the required environment variables:

    • OPENVIKING_URL: The URL of the local or remote server.
    • OPENVIKING_API_KEY: The API key (required for remote servers).

    Implementation

    Initialize OpenVikingMemoryMiddleware and pass it to the middleware list when instantiating your agent. Important: Call memory.close() during application shutdown to flush queued commits.

    Note: OpenViking is disabled unless explicitly added, and service failures do not block the agent run.

    from spoon_ai.agents import SpoonReactAI
    from spoon_ai.middleware import OpenVikingMemoryMiddleware
    
    memory = OpenVikingMemoryMiddleware(
        session_id="stable-conversation-id",
        user="alice",
        actor_peer_id="research-agent",
        provider_timeout_seconds=5.0,
    )
    
    agent = SpoonReactAI(..., middleware=[memory])
    
    # During shutdown:
    # memory.close()
  10. Migrate from legacy LLMFactory to Unified LLM Infrastructure

    main

    The infrastructure is backward compatible with LLMBase and LLMFactory, but new code should use the LLMManager and get_global_registry pattern.

    Step 1: Update Imports

    Before:

    from spoon_ai.llm.factory import LLMFactory
    from spoon_ai.llm.base import LLMBase

    After:

    from spoon_ai.llm import LLMManager, get_global_registry
    from spoon_ai.llm.interface import LLMProviderInterface

    Step 2: Replace Factory Usage

    Before:

    llm = LLMFactory.create("openai", api_key="your-key")
    response = llm.chat("Hello")

    After:

    config_manager = ConfigurationManager()
    llm_manager = LLMManager(config_manager)
    response = await llm_manager.chat([
        {"role": "user", "content": "Hello"}
    ], provider="openai")

    Step 3: Update Custom Providers

    Before:

    class CustomLLM(LLMBase):
        def __init__(self, api_key):
            self.api_key = api_key
        def chat(self, message):
            return response

    After:

    @register_provider("custom")
    class CustomProvider(LLMProviderInterface):
        async def initialize(self, config):
            self.api_key = config["api_key"]
        async def chat(self, messages, **kwargs):
            return LLMResponse(...)
  11. Use x402 Agent Tools and CLI

    main

    When x402 is configured, SpoonReactAI automatically registers two tools:

    • x402_create_payment: Generates signed X-PAYMENT headers.
    • x402_paywalled_request: Negotiates a 402 challenge, signs the payment, and retries the HTTP call.

    Use the bundled CLI for management:

    • requirements: Inspect payment requirements.
    • sign: Sign headers for a specific resource and amount.
    • verify: Verify a base64-encoded header.
    uv run python -m spoon_ai.payments.cli requirements
    uv run python -m spoon_ai.payments.cli sign --amount-usdc 0.05 --resource https://api.example.com/data
    uv run python -m spoon_ai.payments.cli verify <base64-header>
  12. Use the Data Processor Skill

    main

    The data-processor skill provides Python and shell scripts for file analysis and data transformation. It is triggered by keywords like process, analyze, transform, data, parse, or convert, as well as specific patterns such as convert .* to .* or (process|analyze|transform) .*(data|file|json|csv).

    ### Example Tasks
    1. "Analyze this JSON data and tell me about its structure"
    2. "Convert this CSV to JSON format"
    3. "Process this log file and extract key metrics"