@chaoslabs/ai-sdk
v0.0.11
Published
Chaos AI SDK - TypeScript SDK for the Chaos AI API
Maintainers
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-sdkQuick 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_idfield currently accepts a wallet address string. In a future release, this will be replaced with awalletobject 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 MarkdownBlockError 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 operationsTypeScript 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:
- Email: [email protected]
- Documentation: https://docs.chaoslabs.xyz
