X402
Building a Nanoservice Agent
Create a pay-per-use AI agent using DreamsAI's nanoservice infrastructure with built-in micropayments.
This tutorial demonstrates how to build an AI agent that operates as a nanoservice - a pay-per-use service that handles micropayments automatically through the DreamsAI router.
Step 1: Set Up Authentication
First, configure your wallet authentication using a private key. This wallet will handle micropayments for each AI request.
import { createDreamsRouterAuth } from "@daydreamsai/ai-sdk-provider";
import { privateKeyToAccount } from "viem/accounts";
const { dreamsRouter, user } = await createDreamsRouterAuth(
privateKeyToAccount(Bun.env.PRIVATE_KEY as `0x${string}`),
{
payments: {
amount: "100000", // $0.10 USDC per request
network: "base-sepolia",
},
}
);
// Check your balance
console.log("User balance:", user.balance);
The createDreamsRouterAuth
function:
- Takes your wallet's private key (stored securely in environment variables)
- Configures payment settings (amount per request and network)
- Returns a router for model access and user information
Step 2: Configure the Agent
Set up your DreamsAI agent with the authenticated router and desired model.
import { createDreams, LogLevel } from "@daydreamsai/core";
import { cliExtension } from "@daydreamsai/cli";
const agent = createDreams({
logLevel: LogLevel.DEBUG,
model: dreamsRouter("google-vertex/gemini-2.5-flash"),
extensions: [cliExtension], // Add CLI interface for testing
});
Configuration options:
logLevel
: Controls debugging outputmodel
: Specifies the AI model accessed through the routerextensions
: Add capabilities like CLI, Discord, or custom integrations
Step 3: Launch the Nanoservice
Start your agent to begin handling requests with automatic micropayments.
import { createDreamsRouterAuth } from "@daydreamsai/ai-sdk-provider";
import { createDreams, LogLevel } from "@daydreamsai/core";
import { cliExtension } from "@daydreamsai/cli";
import { privateKeyToAccount } from "viem/accounts";
// Step 1: Authentication
const { dreamsRouter, user } = await createDreamsRouterAuth(
privateKeyToAccount(Bun.env.PRIVATE_KEY as `0x${string}`),
{
payments: {
amount: "100000", // $0.10 USDC
network: "base-sepolia",
},
}
);
console.log("Balance:", user.balance);
// Step 2 & 3: Configure and start
createDreams({
logLevel: LogLevel.DEBUG,
model: dreamsRouter("google-vertex/gemini-2.5-flash"),
extensions: [cliExtension],
}).start();
How It Works
Each request to your agent:
- Deducts the configured amount from your wallet balance
- Routes the request to the specified AI model
- Returns the response to your agent
- Handles all blockchain transactions automatically
This creates a true nanoservice where users pay only for what they use, with no subscription fees or upfront costs.