Build an AI Agent

Complete guide to building an autonomous AI agent with Corex402

Agent Architecture

┌────────────────────────────────────────────┐
│            Your AI Agent                    │
├────────────────────────────────────────────┤
│                                             │
│  ┌──────────────────────────────────────┐  │
│  │         Decision Logic               │  │
│  │  • What capability needed?           │  │
│  │  • What's the max price?             │  │
│  │  • Which provider to use?            │  │
│  └────────────┬─────────────────────────┘  │
│               │                             │
│  ┌────────────▼─────────────────────────┐  │
│  │       X402Client (SDK)               │  │
│  │  • createIntent()                    │  │
│  │  • negotiate()                       │  │
│  │  • createSession()                   │  │
│  │  • executeRequest()                  │  │
│  └────────────┬─────────────────────────┘  │
│               │                             │
└───────────────┼─────────────────────────────┘
                │
    ┌───────────▼──────────┐
    │  Solana Blockchain   │
    │  • Payments          │
    │  • Receipts          │
    └──────────────────────┘

Complete Agent Implementation

ai-agent.ts
1import { Connection, Keypair } from '@solana/web3.js';
2import { X402Client } from 'x402pp-client';
3
4class AIAgent {
5  private client: X402Client;
6  private sessions: Map<string, string> = new Map();
7
8  constructor(connection: Connection, wallet: Keypair) {
9    this.client = new X402Client({ connection, wallet });
10  }
11
12  /**
13   * Get data from a provider
14   */
15  async getData(
16    providerUrl: string,
17    capability: string,
18    requestData: any
19  ) {
20    // Check if we have an active session with this provider
21    let sessionId = this.sessions.get(providerUrl);
22    
23    if (!sessionId) {
24      // No session, create one
25      sessionId = await this.createSessionWithProvider(
26        providerUrl,
27        capability
28      );
29      this.sessions.set(providerUrl, sessionId);
30    }
31
32    try {
33      // Execute request
34      const result = await this.client.executeRequest(
35        sessionId,
36        requestData
37      );
38
39      // Verify receipt
40      if (!result.receipt.slaVerification.met) {
41        console.warn('SLA breached, got refund');
42      }
43
44      return result.data;
45    } catch (error) {
46      // Session might be expired or depleted
47      console.log('Session issue, creating new one...');
48      this.sessions.delete(providerUrl);
49      
50      // Retry with new session
51      return this.getData(providerUrl, capability, requestData);
52    }
53  }
54
55  /**
56   * Create session with a provider
57   */
58  private async createSessionWithProvider(
59    providerUrl: string,
60    capability: string
61  ): Promise<string> {
62    // 1. Create Intent
63    const intent = this.client.createIntent({
64      capability,
65      maxPricePerRequest: 0.02,  // Willing to pay up to $0.02
66      token: 'USDC',
67      sla: {
68        maxLatencyMs: 3000,       // Max 3s response
69        minUptimePercent: 99.0
70      }
71    });
72
73    // 2. Negotiate
74    const offer = await this.client.negotiate(providerUrl, intent);
75
76    // 3. Validate offer
77    if (offer.pricePerRequest > intent.maxPricePerRequest) {
78      throw new Error('Price too high');
79    }
80
81    // 4. Create session
82    const session = await this.client.createSession(offer, {
83      depositAmount: 1.0  // 1 USDC should last ~50 requests
84    });
85
86    console.log(`✓ Session created with ${providerUrl}`);
87    return session.sessionId;
88  }
89
90  /**
91   * Cleanup - close all sessions
92   */
93  async cleanup() {
94    for (const sessionId of this.sessions.values()) {
95      try {
96        await this.client.closeSession(sessionId);
97      } catch (error) {
98        console.error('Error closing session:', error);
99      }
100    }
101    this.sessions.clear();
102  }
103}
104
105// Usage
106async function main() {
107  const connection = new Connection('https://api.devnet.solana.com');
108  const wallet = Keypair.generate();
109  
110  const agent = new AIAgent(connection, wallet);
111  
112  // Get weather data
113  const weather = await agent.getData(
114    'https://weather-api.com',
115    'weather-data',
116    { city: 'New York' }
117  );
118  console.log('Weather:', weather);
119  
120  // Get AI inference
121  const inference = await agent.getData(
122    'https://ai-api.com',
123    'gpt-4-inference',
124    { prompt: 'Explain AI' }
125  );
126  console.log('AI Response:', inference);
127  
128  // Cleanup on exit
129  await agent.cleanup();
130}
131
132main();

Multi-Provider Strategy

class SmartAgent {
  async findBestProvider(capability: string) {
    const providers = [
      'https://provider1.com',
      'https://provider2.com',
      'https://provider3.com'
    ];

    // Get offers from all
    const offers = await Promise.all(
      providers.map(async (url, i) => {
        try {
          const intent = this.client.createIntent({
            capability,
            maxPricePerRequest: 0.05,
            token: 'USDC'
          });
          
          const offer = await this.client.negotiate(url, intent);
          return { url, offer };
        } catch {
          return null;
        }
      })
    );

    // Filter valid offers
    const valid = offers.filter(o => o !== null);

    if (valid.length === 0) {
      throw new Error('No providers available');
    }

    // Select cheapest
    const best = valid.sort(
      (a, b) => a.offer.pricePerRequest - b.offer.pricePerRequest
    )[0];

    console.log(`Selected ${best.url} at ${best.offer.pricePerRequest} USDC`);
    
    return best;
  }
}
X (Twitter)