npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@chaoslabs/ai-sdk

v0.0.11

Published

Chaos AI SDK - TypeScript SDK for the Chaos AI API

Readme

Chaos AI SDK

Official TypeScript SDK for the Chaos AI API. Build DeFi-aware applications with portfolio analysis, swap operations, lending, and more.

Installation

npm install @chaoslabs/ai-sdk
# or
bun add @chaoslabs/ai-sdk

Quick Start

1. Get Your API Key

Contact [email protected] to obtain an API key.

2. Set Environment Variables

export CHAOS_API_KEY="ck-your-api-key"

3. Basic Usage

import { Chaos, WALLET_MODEL, extractText, extractBlocks } from '@chaoslabs/ai-sdk';

const chaos = new Chaos({
  apiKey: process.env.CHAOS_API_KEY,
  baseUrl: 'https://ai.chaoslabs.co', // Optional, this is the default
});

const response = await chaos.chat.responses.create({
  model: WALLET_MODEL,
  input: [
    { type: 'message', role: 'user', content: 'What is in my portfolio?' }
  ],
  metadata: {
    user_id: 'user-123',
    session_id: 'session-abc',
    wallet_id: '0x...', // Your wallet address
  },
});

// Extract text content
const text = extractText(response);
console.log(text);

// Extract structured blocks (tables, charts, actions)
const blocks = extractBlocks(response);
for (const block of blocks) {
  console.log(block.type, block);
}

4. Real-Time Streaming (Optional)

Get real-time updates as the AI processes your request:

import { Chaos, WALLET_MODEL, type StreamMessage } from '@chaoslabs/ai-sdk';

const response = await chaos.chat.responses.create({
  model: WALLET_MODEL,
  input: [
    { type: 'message', role: 'user', content: 'What is in my portfolio?' }
  ],
  metadata: { user_id: 'user-123', session_id: 'session-abc', wallet_id: '0x...' },
  onStreamEvent: (msg: StreamMessage) => {
    // Called immediately as each message arrives from the server
    console.log(`[${msg.type}]`, msg.content);
  },
});

Stream Message Types:

| Type | Description | |------|-------------| | agent_status_change | Status updates: processing, done, error | | agent_message | Progress messages during processing | | report | Content blocks as they're generated | | follow_up_suggestions | Suggested follow-up queries | | user_input | Clarification requests |

API Reference

Chaos Client

new Chaos(config: ChaosConfig)

Configuration Options:

| Option | Type | Default | Description | |--------|------|---------|-------------| | apiKey | string | Required | Your Chaos API key | | baseUrl | string | https://ai.chaoslabs.co | API base URL | | timeout | number | 120000 | Request timeout in milliseconds |

Request Options

| Option | Type | Description | |--------|------|-------------| | model | string | Model to use (e.g., WALLET_MODEL) | | input | InputItem[] | Conversation messages | | metadata | RequestMetadata | User, session, and wallet info | | onStreamEvent | (msg: StreamMessage) => void | Real-time streaming callback |

Models

| Model | Description | |-------|-------------| | WALLET_MODEL | Portfolio operations, swaps, lending, staking |

Request Metadata

interface RequestMetadata {
  user_id: string;      // Unique user identifier
  session_id: string;   // Client-generated session ID for conversation continuity
  wallet_id?: string;   // Wallet address (required for WALLET_MODEL)
}

⚠️ Upcoming Change: The wallet_id field currently accepts a wallet address string. In a future release, this will be replaced with a wallet object that includes additional wallet information (chain, connection status, etc.). We will provide migration guidance when this change is released.

Rendering Responses

Responses may contain text, blocks, or both. When rendering responses, text should be displayed before blocks.

Use the extractText and extractBlocks helper functions to extract content from a response:

import { extractText, extractBlocks } from '@chaoslabs/ai-sdk';

const response = await chaos.chat.responses.create({ ... });

// Extract text content (render this first)
const text = extractText(response);
if (text) {
  renderText(text);
}

// Extract blocks (render after text)
const blocks = extractBlocks(response);
for (const block of blocks) {
  renderBlock(block);
}

Response Structure

interface Response {
  id: string;
  object: 'response';
  model: string;
  status: 'completed' | 'failed';
  output: OutputItem[];
  error?: ResponseError;
}

Block Types

The SDK returns structured blocks for rich content:

| Block Type | Description | |------------|-------------| | table | Tabular data (portfolio holdings, positions) | | pie_chart | Distribution charts (allocation breakdown) | | timeseries | Historical data charts | | transaction_action | DeFi operations with primitives and risks | | interactive_card | User prompts and confirmations | | markdown | Rich text content |

Helper Functions

// Extract all text from response
extractText(response: Response): string

// Extract all blocks from response
extractBlocks(response: Response): Block[]

// Check for transaction risks
hasRisks(response: Response): boolean
hasBlockers(response: Response): boolean

// Type guards
isTableBlock(block: Block): block is TableBlock
isPieChartBlock(block: Block): block is PieChartBlock
isTimeseriesBlock(block: Block): block is TimeseriesBlock
isTransactionActionBlock(block: Block): block is TransactionActionBlock
isInteractiveCardBlock(block: Block): block is InteractiveCardBlock
isMarkdownBlock(block: Block): block is MarkdownBlock

Error Handling

import { ChaosError, ChaosTimeoutError } from '@chaoslabs/ai-sdk';

try {
  const response = await chaos.chat.responses.create({ ... });

  if (response.status === 'failed') {
    console.error('Request failed:', response.error);
    return;
  }

  // Process successful response
} catch (error) {
  if (error instanceof ChaosTimeoutError) {
    console.error('Request timed out');
  } else if (error instanceof ChaosError) {
    console.error('API error:', error.message, error.status);
  }
}

Examples

See the examples/ directory for complete examples:

# Install example dependencies
cd examples
bun install

# Run examples
bun run example:01  # Basic query
bun run example:02  # Swap action
bun run example:03  # Multi-turn conversation
bun run example:04  # Block parsing
bun run example:05  # Error handling
bun run example:06  # Lending operations

TypeScript Support

The SDK is written in TypeScript and exports all types:

import type {
  ChaosConfig,
  CreateResponseParams,
  RequestMetadata,
  Response,
  Block,
  TableBlock,
  TransactionActionBlock,
  StreamMessage,
  // ... and more
} from '@chaoslabs/ai-sdk';

Requirements

  • Node.js 18+ or Bun
  • TypeScript 5.0+ (for TypeScript projects)

License

This software is proprietary. See LICENSE for terms.

Support

For questions, issues, or API key requests: