Skip to main content

Agent Loop

Demonstrates an agent making multiple sequential paid API calls with a low balance warning.

What it does

  1. Creates a Crumb instance with a lowBalanceThreshold of 0.5 USDC
  2. Iterates through 5 different search queries
  3. Makes a paid POST /search request for each query
  4. Prints result counts and payment amounts for each call
  5. Shows the final balance after all queries complete

Source

import { Crumb } from 'crumb-alpha-sdk'

const crumb = new Crumb({
privateKey: process.env.TEST_PRIVATE_KEY!,
chain: 'arcTestnet',
lowBalanceThreshold: 0.5,
onLowBalance: (balance) => {
console.warn(`[WARNING] Low balance: ${balance} USDC — consider topping up`)
},
})

const queries = [
'machine learning optimization techniques',
'distributed systems consensus algorithms',
'zero knowledge proof applications',
'autonomous agent architectures 2025',
'quantum computing error correction',
]

async function main() {
console.log('Agent address:', crumb.address)
console.log('Starting balance:', await crumb.balance(), 'USDC')

for (const query of queries) {
console.log(`Querying: "${query}"`)

try {
const result = await crumb.fetch('http://localhost:3001/search', {
method: 'POST',
body: { query },
maxPayment: 0.01,
})

console.log(` Results: ${(result.data as any)?.results?.length ?? 0} items`)
console.log(` Paid: ${result.formattedAmount} USDC`)
} catch (err: any) {
console.error(` Error: ${err.message}`)
break
}
}

console.log('Final balance:', await crumb.balance(), 'USDC')
}

main().catch(console.error)

Running

Requires a provider running on port 3001.

# Terminal 1
npx tsx --env-file=.env examples/provider-express/index.ts

# Terminal 2
npx tsx --env-file=.env examples/agent-loop/index.ts

Expected output

Agent address: 0x22b2...
Starting balance: 10.0 USDC

Querying: "machine learning optimization techniques"
Results: 3 items
Paid: 0.001 USDC

Querying: "distributed systems consensus algorithms"
Results: 3 items
Paid: 0.001 USDC

...

Final balance: 9.995 USDC

If the balance drops below 0.5 USDC during the loop, you'll see the low balance warning.