SAM Framework implements a sophisticated event-driven architecture for AI-powered Solana blockchain operations. The framework combines modular design patterns with async-first principles to deliver high-performance, secure, and extensible agent capabilities.
Event-Driven Core
Async pub/sub system with real-time event streaming and component decoupling.
Plugin Architecture
Extensible tool system with entry point discovery and SDK integration.
Security First
Encrypted key storage, transaction validation, and comprehensive safety controls.
High Performance
uvloop optimization, connection pooling, and efficient RPC management.
Persistent Memory
SQLite-based conversation persistence with context compression.
Configurable Middleware
Pluggable pipeline for logging, rate limiting, and request processing.
sam/core/events.py
)Central nervous system providing async pub/sub messaging between components.
class EventBus: async def publish(self, event: str, payload: Dict) -> None: # Async event publishing def subscribe(self, event: str, handler: Callable) -> None: # Event subscription management
Key Events:
tool.called
- Tool execution initiatedtool.succeeded
- Tool completed successfullytool.failed
- Tool execution failedllm.usage
- Token usage trackingagent.session.started
- Session lifecyclesam/core/agent.py
)Orchestrates AI conversation flow with advanced tool calling and loop prevention.
class SAMAgent: def __init__( self, llm: LLMProvider, tools: ToolRegistry, memory: MemoryManager, system_prompt: str, event_bus: EventBus ): # Full initialization with event integration async def run(self, user_input: str, session_id: str) -> str: # Advanced execution loop with tool loop prevention
Features:
sam/core/llm_provider.py
)Multi-provider abstraction supporting OpenAI, Anthropic, xAI, and local models.
class LLMProvider(ABC): @abstractmethod async def chat_completion( self, messages: List[Dict], tools: List[Dict] = None ) -> ChatResponse: # Provider-specific implementation class LLMProviderFactory: @staticmethod def create(provider_name: str) -> LLMProvider: # Factory pattern for provider instantiation
Supported Providers:
sam/core/tools.py
)Centralized tool management with middleware pipeline and plugin support.
class ToolRegistry: def __init__(self, middlewares: List[Middleware]): self._middlewares = middlewares self._tools = {} async def call( self, name: str, args: Dict, context: ToolContext ) -> Dict: # Middleware pipeline execution
Middleware Types:
sam/core/memory.py
)Advanced SQLite-based persistent storage with context compression and session management.
class MemoryManager: async def save_session(self, session_id: str, messages: List[Dict]): # Persist conversation with compression async def load_session(self, session_id: str) -> List[Dict]: # Retrieve and decompress conversation history async def compact_conversation(self, session_id: str) -> str: # Compress old messages to maintain context window
Features:
sam/core/builder.py
)Factory pattern implementation for modular agent construction and dependency injection.
class AgentBuilder: def __init__(self): self._llm_provider = None self._tool_registry = None self._memory_manager = None self._middlewares = [] def with_llm_provider(self, provider: LLMProvider) -> 'AgentBuilder': # Fluent interface for configuration async def build(self) -> SAMAgent: # Async construction with validation
Benefits:
sam/integrations/solana/
)Native Solana blockchain operations with comprehensive RPC integration.
class SolanaTools: def __init__(self, rpc_url: str, private_key: Optional[str] = None): # Initialize with secure key management async def get_balance(self, address: Optional[str] = None) -> Dict[str, Any]: # Complete wallet overview with token balances
Capabilities:
sam/integrations/pump_fun.py
)Real-time memecoin trading on the Pump.fun platform.
class PumpFunTools: async def pump_fun_buy(self, mint: str, amount: float, slippage: int) -> Dict[str, Any]: # Execute Pump.fun token purchases
sam/integrations/jupiter.py
)DEX aggregation for optimal Solana token swaps.
class JupiterTools: async def get_swap_quote(self, input_mint: str, output_mint: str, amount: int) -> Dict[str, Any]: # Get optimized swap quotes across multiple DEXes
sam/integrations/dexscreener.py
)Real-time market data and trading pair information.
class DexScreenerTools: async def search_pairs(self, query: str) -> Dict[str, Any]: # Search trading pairs by token or query
sam/integrations/search.py
)Internet search capabilities via Brave Search API.
class SearchTools: async def search_web(self, query: str) -> Dict[str, Any]: # Web search with result summarization
SAM supports external tools and components via Python entry points for maximum extensibility.
# setup.py or pyproject.toml [project.entry-points."sam.plugins"] my_trading_tools = "my_package.tools:register" [project.entry-points."sam.llm_providers"] custom_llm = "my_package.llm:create_provider" [project.entry-points."sam.memory_backends"] redis_memory = "my_package.memory:create_backend" [project.entry-points."sam.secure_storage"] cloud_keyring = "my_package.security:create_storage"
# my_package/tools.py from sam.core.tools import Tool, ToolRegistry async def my_custom_tool(args: dict) -> dict: # Custom tool implementation return {"result": "custom logic executed"} def register(registry: ToolRegistry, agent=None): """Register custom tools with the SAM agent.""" registry.register(Tool( name="my_custom_tool", description="Custom trading tool", input_schema={ "type": "object", "properties": { "param": {"type": "string", "description": "Tool parameter"} }, "required": ["param"] }, handler=my_custom_tool ))
# my_package/llm.py from sam.core.llm_provider import LLMProvider from sam.core.settings import Settings class CustomLLMProvider(LLMProvider): def __init__(self, api_key: str, model: str): self.api_key = api_key self.model = model async def chat_completion(self, messages, tools=None): # Custom LLM implementation return ChatResponse(...) def create_provider(settings: Settings = None) -> LLMProvider: """Factory function for custom LLM provider.""" return CustomLLMProvider( api_key=settings.CUSTOM_API_KEY, model=settings.CUSTOM_MODEL )
# Load custom plugins export SAM_PLUGINS="my_package.tools,vendor_package.tools" # Use custom memory backend export SAM_MEMORY_BACKEND="my_package.memory:create_backend" # Custom middleware configuration export SAM_MIDDLEWARE_JSON='{"logging": {"include_args": true}}'
# sam/utils/secure_storage.py class SecureStorage: def store_private_key(self, key_id: str, private_key: str): # Store encrypted keys in system keyring def get_private_key(self, key_id: str) -> Optional[str]: # Retrieve and decrypt keys securely
Features:
graph TD A[User Input] --> B[SAM Agent] B --> C[LLM Provider] C --> D{Tool Call?} D -->|Yes| E[Tool Registry] D -->|No| F[Final Response] E --> G[Execute Tool] G --> H[Tool Result] H --> C F --> I[Memory Manager] I --> J[Persist Context] G --> K[Error Handler] K --> L[Graceful Degradation]
# sam/config/settings.py class Settings: # Centralized configuration management OPENAI_API_KEY: str SAM_FERNET_KEY: Optional[str] # ... other settings
tests/
โโโ test_tools.py # Tool functionality
โโโ test_integration.py # Cross-component tests
โโโ test_crypto.py # Security features
โโโ test_memory.py # Persistence layer
โโโ test_rate_limiter.py # Performance controls
Production Checklist:
RATE_LIMITING_ENABLED=true
)MAX_TRANSACTION_SOL=10.0
)LOG_LEVEL=WARNING
)