Architecture

Chain Mind Framework Overview

The Chain Mind Framework is designed as a modular, scalable, and high-performance system that facilitates the deployment, interaction, and management of AI agents.


1. Core Components

1.1 Backend API Layer

  • Purpose: The backend serves as the primary interface for users to interact with AI agents.

  • Technology Stack: Built with Node.js and uses Express for routing and API endpoints.

  • API Style: Supports RESTful operations for agent queries, token management, and trading.

  • Key Integrations: Supabase for data persistence and Solana for blockchain operations (if applicable).

Key Responsibilities

  • Manage agent lifecycle (deployment, interaction, decommission).

  • Query and handle agent-specific data from blockchains and external APIs.

  • Enable seamless interaction through HTTP methods (GET, POST, etc.).

tsCopyEditimport express from 'express';
import { interactAgent } from './interactAgent';

const app = express();
app.use(express.json());

app.post('/api/agent/:agentName/interact', async (req, res) => {
  const { agentName } = req.params;
  const { message } = req.body;
  const response = await interactAgent(agentName, message);
  res.json({ response });
});

app.listen(3000, () => console.log('Server is running on port 3000'));

1.2 Blockchain Integration

  • Supported Chain: Solana is an example of a high-speed, low-cost blockchain.

  • Library: Interact with Solana via @solana/web3.js for token creation, management, and on-chain data queries.

  • Benefits:

    • Transparency and immutability by storing critical agent data on-chain.

    • Real-time data queries via Bitquery APIs (optional).

Key Features

  • Efficient token management and trading operations on the Solana network.

  • Real-time blockchain data (e.g., top holders, token supply).

tsCopyEditimport { Connection, clusterApiUrl } from '@solana/web3.js';

const connection = new Connection(clusterApiUrl('mainnet-beta'), 'confirmed');

async function getTokenBalance(mintAddress: string): Promise<void> {
  const balance = await connection.getTokenSupply(mintAddress);
  console.log(`Token Supply: ${balance.value.uiAmount}`);
}

// Example usage
getTokenBalance('6LKbpcg2fQ84Ay3kKXVyo3bHUGe3s36g9EVbKYSupump');

1.3 AI Engine

  • Powered By: OpenAI APIs for generating intelligent and context-aware responses.

  • Customization: Each agent can be configured with unique behaviors and knowledge bases.

  • Key Features:

    • Flexible agent behavior configuration.

    • Scalable AI query handling using GPT-based models.

    • Natural Language Processing (NLP) for advanced user interaction.

tsCopyEditimport { Configuration, OpenAIApi } from 'openai';

const openai = new OpenAIApi(
  new Configuration({ apiKey: process.env.OPENAI_API_KEY })
);

export async function askAI(question: string): Promise<string> {
  const response = await openai.createCompletion({
    model: 'text-davinci-003',
    prompt: question,
    max_tokens: 200,
  });
  return response.data.choices[0].text.trim();
}

1.4 Supabase Integration

  • Purpose: Acts as the centralized database for storing agent metadata, user interactions, and analytics.

  • Real-Time Data: Supabase offers real-time data synchronization for swift coordination between agents and users.

  • Security: Handles authentication, row-level security, and ownership validations.

Key Responsibilities

  • Store agent details (names, addresses, metadata).

  • Maintain logs of user interactions and performance metrics.

tsCopyEditimport { createClient } from '@supabase/supabase-js';

const supabaseUrl = process.env.SUPABASE_URL!;
const supabaseAnonKey = process.env.SUPABASE_ANON_KEY!;
const supabase = createClient(supabaseUrl, supabaseAnonKey);

export async function storeAgentData(agentName: string, data: any): Promise<void> {
  const { error } = await supabase
    .from('agents')
    .insert({
      agent_name: agentName,
      metadata: data,
      created_at: new Date().toISOString(),
    });
    
  if (error) {
    console.error('Failed to store agent data:', error.message);
    return;
  }
  console.log('Agent data stored successfully!');
}

2. Layers of Architecture

2.1 User Interaction Layer

  • Methods of Interaction:

    1. Command-Line Tools (e.g., npm run interactMind)

    2. RESTful API Endpoints (e.g., cURL commands)

    3. Web Interfaces or third-party applications

  • Goal: Provide an intuitive interface for both developers and end-users.

bashCopyEditcurl -X POST "https://api.chainmind.network/api/agent/"Demo Mind"/interact" \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello, Demo Mind!"}'

2.2 Middleware Layer

  • Function: Orchestrates and secures communication between the User Interaction Layer and Backend API.

  • Features:

    • Authentication via API keys or tokens.

    • Input validation and sanitization to prevent unauthorized access or misuse.

tsCopyEditfunction validateRequest(req, res, next) {
  if (!req.headers['x-api-key']) {
    return res.status(401).json({ error: 'Unauthorized access' });
  }
  next();
}

app.use(validateRequest);

2.3 Backend Service Layer

  • Core Functions:

    • Handle incoming API requests and route them to the correct services.

    • Manage blockchain interactions (e.g., Solana).

    • Communicate with external APIs like OpenAI and Bitquery.

tsCopyEditasync function fetchTrendingTokens(): Promise<void> {
  const query = `
    query {
      Solana {
        DEXTradeByTokens(limit: { count: 5 }) {
          Trade {
            Currency {
              Name
              MintAddress
            }
          }
        }
      }
    }
  `;
  const response = await fetch(process.env.BITQUERY_API_URL!, {
    method: 'POST',
    headers: {
      'X-API-KEY': process.env.BITQUERY_API_KEY!,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ query }),
  });
  
  const data = await response.json();
  console.log(data);
}

2.4 Data Storage Layer

  • Supabase

    • Stores agent metadata, logs, and user interactions.

    • Provides secure, real-time data synchronization.

  • Solana Blockchain (Optional)

    • Immutable storage for on-chain data such as token details, ownership, and transaction history.


3. Key Integrations

Technology

Purpose

OpenAI

AI-powered interactions for agent behavior.

Solana

High-performance blockchain for token and transaction management.

Supabase

Cloud database for storing agent data and logs.

Bitquery

Blockchain analytics and querying capabilities.

Node.js

Backend framework for RESTful APIs and business logic.

TypeScript

Strongly typed language for robust, efficient development.


4. Scalability and Extensibility

  • Horizontal Scalability

    • Deploy multiple agents or services independently.

    • Scale backend services and API handling as demand grows.

  • Extensibility

    • Easily integrate additional blockchains or AI engines.

    • Add new features via modular components and APIs.


5. Security

  • API Authentication: Using environment variables, API keys, or tokens.

  • Data Integrity: Guaranteed by storing critical data on blockchain (where relevant).

  • Supabase Security: Row-level security rules and user-based policies to protect data.


6. Example Workflow

Agent Interaction Workflow

  1. User Input A user sends a request via CLI or API, for example:

    npm run interactMind Aura ask "Hello!"
  2. Middleware Validation The request is validated to ensure it has proper authentication headers or tokens.

  3. AI Engine Processing The AI engine processes the user request and generates a response.

  4. Blockchain Query (if needed) Relevant on-chain data (e.g., token holders, supply) is fetched via Bitquery or @solana/web3.js.

  5. Response The final processed message or data is returned to the user via CLI or API.


7. Future Enhancements

  • Multi-Chain Support: Expand compatibility to additional blockchain networks.

  • Analytics Dashboard: A more advanced UI for monitoring agent performance and usage.

  • Plugin-Based Architecture: Facilitate third-party integrations with minimal code changes.


By leveraging Supabase for database needs and the Chain Mind Framework for AI and blockchain integration, you can build powerful AI agents that interact seamlessly with both users and on-chain data.

Last updated