API Reference

API Reference

📚 API Overview

This reference documents the key classes, methods, and interfaces of the SAM Framework. The API is designed to be modular and extensible, with clear separation of concerns.

Core Classes

Main framework components and interfaces

Integrations

Blockchain and DeFi service integrations

Security

Security utilities and key management

🧠 Core Classes

SAMAgent

The main agent orchestrator that manages AI conversations and tool execution.

class SAMAgent:
    def __init__(self, llm: LLMProvider, tools: ToolRegistry, memory: MemoryManager, system_prompt: str):
        """Initialize the SAM agent.

        Args:
            llm: LLM provider for AI interactions
            tools: Registry of available tools
            memory: Memory manager for conversation persistence
            system_prompt: System prompt for the agent
        """

Key Methods

async def run(self, user_input: str, session_id: str) -> str:
    """Execute agent logic for user input.

    Args:
        user_input: User's natural language input
        session_id: Unique session identifier

    Returns:
        Agent's response string
    """

async def clear_context(self, session_id: str) -> str:
    """Clear conversation context for a session.

    Args:
        session_id: Session to clear

    Returns:
        Status message
    """

async def compact_conversation(self, session_id: str) -> str:
    """Compact conversation by summarizing older messages.

    Args:
        session_id: Session to compact

    Returns:
        Status message
    """

Properties

  • session_stats: Dictionary containing usage statistics
  • tool_callback: Optional callback for tool execution notifications

LLMProvider

Abstracts OpenAI API interactions with robust error handling.

class LLMProvider:
    def __init__(self, api_key: str, model: str = "gpt-4o", base_url: Optional[str] = None):
        """Initialize LLM provider.

        Args:
            api_key: OpenAI API key
            model: Model name (default: gpt-4o)
            base_url: Custom API endpoint
        """

Key Methods

async def chat_completion(self, messages: List[Dict], tools: List[Dict] = None) -> ChatResponse:
    """Get chat completion from LLM.

    Args:
        messages: Conversation messages
        tools: Available tools for function calling

    Returns:
        ChatResponse with content and usage data
    """

ToolRegistry

Manages tool registration and execution with type safety.

class ToolRegistry:
    def __init__(self):
        """Initialize empty tool registry."""

Key Methods

def register(self, tool: Tool):
    """Register a tool in the registry.

    Args:
        tool: Tool instance to register
    """

async def call(self, name: str, args: Dict[str, Any]) -> Dict[str, Any]:
    """Execute a tool by name.

    Args:
        name: Tool name to execute
        args: Arguments for the tool

    Returns:
        Tool execution result
    """

def list_specs(self) -> List[Dict[str, Any]]:
    """Get specifications for all registered tools.

    Returns:
        List of tool specifications
    """

MemoryManager

Handles conversation persistence and context management.

class MemoryManager:
    def __init__(self, db_path: str):
        """Initialize memory manager.

        Args:
            db_path: Path to SQLite database file
        """

Key Methods

async def save_session(self, session_id: str, messages: List[Dict]):
    """Save conversation messages for a session.

    Args:
        session_id: Unique session identifier
        messages: Messages to save
    """

async def load_session(self, session_id: str) -> List[Dict]:
    """Load conversation messages for a session.

    Args:
        session_id: Session to load

    Returns:
        List of conversation messages
    """

async def clear_session(self, session_id: str):
    """Clear all messages for a session.

    Args:
        session_id: Session to clear
    """

🔗 Integration Classes

SolanaTools

Core Solana blockchain operations and wallet management.

class SolanaTools:
    def __init__(self, rpc_url: str, private_key: Optional[str] = None):
        """Initialize Solana tools.

        Args:
            rpc_url: Solana RPC endpoint URL
            private_key: Optional private key for transactions
        """

Key Methods

async def get_balance(self, address: Optional[str] = None) -> Dict[str, Any]:
    """Get SOL and token balances.

    Args:
        address: Optional address (uses wallet if not provided)

    Returns:
        Balance information with USD values
    """

async def transfer_sol(self, to_address: str, amount: float) -> Dict[str, Any]:
    """Transfer SOL to another address.

    Args:
        to_address: Recipient address
        amount: Amount of SOL to transfer

    Returns:
        Transaction result
    """

async def get_token_data(self, mint_address: str) -> Dict[str, Any]:
    """Get comprehensive token metadata.

    Args:
        mint_address: Token mint address

    Returns:
        Token metadata and information
    """

PumpFunTools

Pump.fun trading platform integration.

class PumpFunTools:
    def __init__(self, solana_tools=None):
        """Initialize Pump.fun tools.

        Args:
            solana_tools: SolanaTools instance for transactions
        """

Key Methods

async def pump_fun_buy(self, mint: str, amount: float, slippage: int = 5) -> Dict[str, Any]:
    """Execute Pump.fun token purchase.

    Args:
        mint: Token mint address
        amount: SOL amount to spend
        slippage: Slippage tolerance percentage

    Returns:
        Transaction result
    """

async def pump_fun_sell(self, mint: str, percentage: int, slippage: int = 5) -> Dict[str, Any]:
    """Execute Pump.fun token sale.

    Args:
        mint: Token mint address
        percentage: Percentage of holdings to sell
        slippage: Slippage tolerance percentage

    Returns:
        Transaction result
    """

async def get_pump_token_info(self, mint: str) -> Dict[str, Any]:
    """Get Pump.fun token information.

    Args:
        mint: Token mint address

    Returns:
        Token information and statistics
    """

JupiterTools

Jupiter DEX aggregator integration.

class JupiterTools:
    def __init__(self, solana_tools=None):
        """Initialize Jupiter tools.

        Args:
            solana_tools: SolanaTools instance for transactions
        """

Key Methods

async def get_quote(self, input_mint: str, output_mint: str, amount: int, slippage_bps: int = 50) -> Dict[str, Any]:
    """Get swap quote from Jupiter.

    Args:
        input_mint: Input token mint
        output_mint: Output token mint
        amount: Amount to swap (in smallest units)
        slippage_bps: Slippage in basis points

    Returns:
        Quote information
    """

async def create_swap_transaction(self, user_public_key: str, quote_response: Dict[str, Any], priority_fee: int = 1000) -> Dict[str, Any]:
    """Create Jupiter swap transaction.

    Args:
        user_public_key: User's public key
        quote_response: Quote from get_quote
        priority_fee: Priority fee in lamports

    Returns:
        Transaction data
    """

DexScreenerTools

Market data and trading pair information.

class DexScreenerTools:
    def __init__(self):
        """Initialize DexScreener tools."""

Key Methods

async def search_pairs(self, query: str, limit: int = 20) -> Dict[str, Any]:
    """Search for trading pairs.

    Args:
        query: Search query
        limit: Maximum results

    Returns:
        Trading pair results
    """

async def get_trending_pairs(self, chain: str = "solana", limit: int = 20) -> Dict[str, Any]:
    """Get trending pairs by chain.

    Args:
        chain: Blockchain name
        limit: Maximum results

    Returns:
        Trending pairs data
    """

async def get_solana_pair(self, pair_address: str) -> Dict[str, Any]:
    """Get detailed pair information.

    Args:
        pair_address: Trading pair address

    Returns:
        Detailed pair data
    """

🔒 Security Classes

SecureStorage

System keyring integration for secure credential storage.

class SecureStorage:
    def __init__(self, fernet_key: str):
        """Initialize secure storage.

        Args:
            fernet_key: Fernet encryption key
        """

Key Methods

def store_private_key(self, key_id: str, private_key: str) -> bool:
    """Store encrypted private key in system keyring.

    Args:
        key_id: Unique key identifier
        private_key: Private key to store

    Returns:
        Success status
    """

def get_private_key(self, key_id: str) -> Optional[str]:
    """Retrieve and decrypt private key.

    Args:
        key_id: Key identifier

    Returns:
        Decrypted private key or None
    """

def test_keyring_access(self) -> Dict[str, Any]:
    """Test system keyring availability.

    Returns:
        Keyring status information
    """

Crypto Utilities

Encryption and decryption utilities.

# sam/utils/crypto.py

def encrypt_private_key(private_key: str, fernet_key: str) -> str:
    """Encrypt private key with Fernet.

    Args:
        private_key: Plain text private key
        fernet_key: Fernet encryption key

    Returns:
        Base64 encoded encrypted key
    """

def decrypt_private_key(encrypted_key: str, fernet_key: str) -> str:
    """Decrypt private key with Fernet.

    Args:
        encrypted_key: Encrypted private key
        fernet_key: Fernet encryption key

    Returns:
        Plain text private key
    """

def generate_encryption_key() -> str:
    """Generate new Fernet encryption key.

    Returns:
        Base64 encoded Fernet key
    """

🛠️ Utility Classes

RateLimiter

Request throttling and abuse prevention.

class RateLimiter:
    def __init__(self, requests_per_minute: int = 60):
        """Initialize rate limiter.

        Args:
            requests_per_minute: Maximum requests per minute
        """

Key Methods

async def check_limit(self, key: str) -> bool:
    """Check if request is within rate limits.

    Args:
        key: Rate limit key (usually user/API identifier)

    Returns:
        True if within limits, False if exceeded
    """

HTTP Client

Shared HTTP client with connection pooling.

# sam/utils/http_client.py

async def get_session() -> aiohttp.ClientSession:
    """Get shared HTTP client session.

    Returns:
        Configured aiohttp session
    """

async def cleanup_http_client():
    """Cleanup HTTP client resources."""

Settings

Centralized configuration management.

class Settings:
    """Application settings loaded from environment variables."""

    # LLM Configuration
    OPENAI_API_KEY: str = os.getenv("OPENAI_API_KEY", "")
    OPENAI_MODEL: str = os.getenv("OPENAI_MODEL", "gpt-4o")

    # Solana Configuration
    SAM_SOLANA_RPC_URL: str = os.getenv("SAM_SOLANA_RPC_URL", "https://api.mainnet-beta.solana.com")

    # Security Configuration
    SAM_FERNET_KEY: Optional[str] = os.getenv("SAM_FERNET_KEY")

📋 Tool Specifications

ToolSpec

Standardized tool definition format.

class ToolSpec(BaseModel):
    """Tool specification for LLM function calling."""

    name: str
    description: str
    input_schema: Dict[str, Any]  # JSON Schema format

Tool

Executable tool wrapper.

class Tool:
    def __init__(self, spec: ToolSpec, handler: Handler):
        """Initialize tool.

        Args:
            spec: Tool specification
            handler: Async handler function
        """

🔧 Error Handling

Custom Exceptions

class SAMError(Exception):
    """Base SAM framework exception."""
    pass

class ConfigurationError(SAMError):
    """Configuration-related errors."""
    pass

class SecurityError(SAMError):
    """Security-related errors."""
    pass

Error Handling Utilities

# sam/utils/error_messages.py

async def handle_error_gracefully(error: Exception, context: Dict[str, Any]) -> Dict[str, Any]:
    """Handle errors with appropriate user messages.

    Args:
        error: Exception that occurred
        context: Context information for error handling

    Returns:
        Error response dictionary
    """

📊 Type Definitions

Common Types

from typing import Dict, Any, List, Optional, Callable, Awaitable

# Tool handler function type
Handler = Callable[[Dict[str, Any]], Awaitable[Dict[str, Any]]]

# Message format for LLM conversations
Message = Dict[str, str]  # {"role": "user", "content": "message"}

# Tool call specification
ToolCall = Dict[str, Any]  # OpenAI tool call format

# API response format
APIResponse = Dict[str, Any]

🚀 Integration Points

Custom Tool Registration

# Register a custom tool
async def my_custom_tool(args: Dict[str, Any]) -> Dict[str, Any]:
    # Custom tool implementation
    return {"result": "custom response"}

tool_spec = ToolSpec(
    name="my_custom_tool",
    description="Description of custom tool",
    input_schema={
        "type": "object",
        "properties": {
            "param": {"type": "string", "description": "Parameter description"}
        },
        "required": ["param"]
    }
)

tool = Tool(spec=tool_spec, handler=my_custom_tool)
tool_registry.register(tool)

Custom Integration

# Create custom integration class
class MyIntegration:
    def __init__(self, api_key: str):
        self.api_key = api_key

    async def my_method(self, param: str) -> Dict[str, Any]:
        # Custom integration logic
        return {"data": f"processed {param}"}

# Register tools from integration
def create_my_tools(integration: MyIntegration) -> List[Tool]:
    async def tool_handler(args):
        return await integration.my_method(args["param"])

    spec = ToolSpec(
        name="my_integration_tool",
        description="Custom integration tool",
        input_schema={
            "type": "object",
            "properties": {"param": {"type": "string"}},
            "required": ["param"]
        }
    )

    return [Tool(spec=spec, handler=tool_handler)]

📖 Additional Resources

  • Source Code: Explore the full implementation in sam/ directory
  • Examples: Check tests/ for usage examples
  • Extending: See Development Guide for adding new tools
  • Security: Review Security Guide for secure implementation