Helper Functions
Updated
The SDK exports a comprehensive set of helper functions for working with blocks, primitives, tables, charts, and risk data. All functions are imported from @chaoslabs/ai-sdk.
Block Extraction
Extract blocks of a specific type from a ChatCreateResponse.
function extractTableBlocks(response: ChatCreateResponse): TableBlock[]
function extractChartBlocks(response: ChatCreateResponse): ChartBlock[]
function extractTransactionBlocks(response: ChatCreateResponse): ActionBlock[]
function extractMarkdownBlocks(response: ChatCreateResponse): MarkdownBlock[]
function extractInteractiveBlocks(response: ChatCreateResponse): InteractiveBlock[]
function extractInfoBlocks(response: ChatCreateResponse): AlertBlock[]
function extractCodeBlocks(response: ChatCreateResponse): CodeBlock[]
function extractFormBlocks(response: ChatCreateResponse): FormBlock[]Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
| Function | Returns | Description |
|---|---|---|
extractTableBlocks | TableBlock[] | All table blocks |
extractChartBlocks | ChartBlock[] | All chart blocks (pie, bar, timeseries) |
extractTransactionBlocks | ActionBlock[] | All transaction action blocks |
extractMarkdownBlocks | MarkdownBlock[] | All markdown blocks |
extractInteractiveBlocks | InteractiveBlock[] | All interactive prompt blocks |
extractInfoBlocks | AlertBlock[] | All alert blocks |
extractCodeBlocks | CodeBlock[] | All code blocks |
extractFormBlocks | FormBlock[] | All form blocks |
import {
extractTableBlocks,
extractChartBlocks,
extractTransactionBlocks,
} from '@chaoslabs/ai-sdk';
const tables = extractTableBlocks(response);
const charts = extractChartBlocks(response);
const actions = extractTransactionBlocks(response);
console.log(`${tables.length} tables, ${charts.length} charts, ${actions.length} actions`);Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
Block Search
Find specific blocks by title or content.
function findTableByTitle(
response: ChatCreateResponse,
title: string
): TableBlock | undefined
function findChartByTitle(
response: ChatCreateResponse,
title: string
): ChartBlock | undefined
function findTransactionsByPrimitive(
response: ChatCreateResponse,
primitiveType: string
): ActionBlock[]Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
| Function | Returns | Description |
|---|---|---|
findTableByTitle | TableBlock | undefined | First table whose title contains the search string (case-insensitive) |
findChartByTitle | ChartBlock | undefined | First chart whose title contains the search string (case-insensitive) |
findTransactionsByPrimitive | ActionBlock[] | All action blocks containing a primitive of the given type |
import {
findTableByTitle,
findChartByTitle,
findTransactionsByPrimitive,
PRIMITIVE_SWAP,
} from '@chaoslabs/ai-sdk';
// Find a specific table
const portfolioTable = findTableByTitle(response, 'portfolio');
if (portfolioTable) {
console.log('Found portfolio table with', portfolioTable.tableRows.length, 'rows');
}
// Find a chart
const allocationChart = findChartByTitle(response, 'allocation');
// Find all swap transactions
const swapActions = findTransactionsByPrimitive(response, PRIMITIVE_SWAP);Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
Primitive Extraction
Extract and filter transaction primitives from action blocks.
function extractPrimitives(response: ChatCreateResponse): Primitive[]
function extractPrimitivesByType(
response: ChatCreateResponse,
primitiveType: string
): Primitive[]
function getPrimitiveTypes(response: ChatCreateResponse): string[]Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
| Function | Returns | Description |
|---|---|---|
extractPrimitives | Primitive[] | All primitives from all action blocks |
extractPrimitivesByType | Primitive[] | Primitives matching a specific type string |
getPrimitiveTypes | string[] | Unique primitive type strings in the response |
import {
extractPrimitives,
extractPrimitivesByType,
getPrimitiveTypes,
PRIMITIVE_LENDING_DEPOSIT,
isLendingDepositPrimitive,
} from '@chaoslabs/ai-sdk';
// Get all primitives
const primitives = extractPrimitives(response);
console.log(`Total primitives: ${primitives.length}`);
// Get unique types
const types = getPrimitiveTypes(response);
console.log('Primitive types:', types);
// e.g., ['swap', 'lending_deposit']
// Filter by type
const deposits = extractPrimitivesByType(response, PRIMITIVE_LENDING_DEPOSIT);
for (const p of deposits) {
if (isLendingDepositPrimitive(p)) {
console.log(`Deposit ${p.params.amount} on ${p.params.chain}`);
}
}Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
Table Utilities
Work with TableBlock data: convert to objects, extract columns, search rows, and get dimensions.
function tableToObjects<T extends Record<string, unknown>>(table: TableBlock): T[]
function getTableColumn(table: TableBlock, columnName: string): unknown[]
function findTableRow(
table: TableBlock,
columnName: string,
value: unknown
): unknown[] | undefined
function getTableDimensions(table: TableBlock): { columns: number; rows: number }Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
| Function | Returns | Description |
|---|---|---|
tableToObjects<T> | T[] | Convert table rows to typed objects using headers as keys |
getTableColumn | unknown[] | Extract all values from a named column |
findTableRow | unknown[] | undefined | Find the first row where a column matches a value |
getTableDimensions | { columns, rows } | Get the number of columns and rows |
import {
extractTableBlocks,
tableToObjects,
getTableColumn,
findTableRow,
getTableDimensions,
} from '@chaoslabs/ai-sdk';
const table = extractTableBlocks(response)[0];
if (table) {
// Dimensions
const dims = getTableDimensions(table);
console.log(`${dims.columns} columns x ${dims.rows} rows`);
// Convert to objects
interface AssetRow {
Asset: string;
Balance: string;
Value: string;
}
const rows = tableToObjects<AssetRow>(table);
for (const row of rows) {
console.log(`${row.Asset}: ${row.Balance} (${row.Value})`);
}
// Extract a single column
const assets = getTableColumn(table, 'Asset');
console.log('Assets:', assets);
// Find a specific row
const ethRow = findTableRow(table, 'Asset', 'ETH');
if (ethRow) {
console.log('ETH row:', ethRow);
}
}Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
Chart Utilities
Extract data, totals, and percentages from PieChartBlock charts.
function getChartData(chart: PieChartBlock): Array<{ label: string; value: number }>
function getChartTotal(chart: PieChartBlock): number
function getChartPercentages(
chart: PieChartBlock
): Array<{ label: string; percentage: number }>Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
| Function | Returns | Description |
|---|---|---|
getChartData | Array<{ label, value }> | Flatten series data into label-value pairs |
getChartTotal | number | Sum of all chart segment values |
getChartPercentages | Array<{ label, percentage }> | Each segment as a percentage of the total |
import {
extractChartBlocks,
isPieChartBlock,
getChartData,
getChartTotal,
getChartPercentages,
} from '@chaoslabs/ai-sdk';
const charts = extractChartBlocks(response);
for (const chart of charts) {
if (isPieChartBlock(chart)) {
const data = getChartData(chart);
const total = getChartTotal(chart);
const percentages = getChartPercentages(chart);
console.log(`Chart: ${chart.title}`);
console.log(`Total value: $${total.toLocaleString()}`);
for (const item of percentages) {
console.log(` ${item.label}: ${item.percentage.toFixed(1)}%`);
}
}
}Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
Risk Utilities
Analyze risk data from action blocks across a response.
function getAllWarnings(response: ChatCreateResponse): RiskInfoItem[]
function getAllBlockers(response: ChatCreateResponse): RiskInfoItem[]
function getHighestRiskLevel(response: ChatCreateResponse): RiskLevel | undefined
// RiskLevel is derived from the Risks interface
type RiskLevel = 'low' | 'medium' | 'high' | 'critical';Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
| Function | Returns | Description |
|---|---|---|
getAllWarnings | RiskInfoItem[] | All warning items from all action blocks |
getAllBlockers | RiskInfoItem[] | All blocker items from all action blocks |
getHighestRiskLevel | RiskLevel | undefined | The highest risk level across all action blocks |
import {
getAllWarnings,
getAllBlockers,
getHighestRiskLevel,
} from '@chaoslabs/ai-sdk';
const warnings = getAllWarnings(response);
const blockers = getAllBlockers(response);
const highestRisk = getHighestRiskLevel(response);
console.log(`Highest risk: ${highestRisk ?? 'none'}`);
console.log(`Warnings: ${warnings.length}`);
console.log(`Blockers: ${blockers.length}`);
for (const warning of warnings) {
console.log(` [WARN] ${warning.title}: ${warning.message}`);
if (warning.impact) {
console.log(` Metric: ${warning.impact.metric}`);
console.log(` Current: ${warning.impact.current} -> Projected: ${warning.impact.projected}`);
}
}
for (const blocker of blockers) {
console.log(` [BLOCK] ${blocker.title}: ${blocker.message}`);
}Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
Block Statistics
Count and check for blocks by type.
function countBlocksByType(response: ChatCreateResponse): BlockTypeCounts
function hasBlocks(response: ChatCreateResponse): boolean
function hasBlockType(response: ChatCreateResponse, type: Block['type']): boolean
// BlockTypeCounts is a Record mapping each block type to its count
type BlockTypeCounts = Record<Block['type'], number>;
// Equivalent to:
// {
// table: number;
// pie_chart: number;
// bar_chart: number;
// timeseries_chart: number;
// action: number;
// markdown: number;
// interactive: number;
// alert: number;
// code: number;
// form: number;
// }Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
| Function | Returns | Description |
|---|---|---|
countBlocksByType | BlockTypeCounts | Count of each block type in the response |
hasBlocks | boolean | Whether the response contains any blocks |
hasBlockType | boolean | Whether the response contains a specific block type |
import {
countBlocksByType,
hasBlocks,
hasBlockType,
} from '@chaoslabs/ai-sdk';
if (!hasBlocks(response)) {
console.log('Response contains only text, no structured blocks.');
} else {
const counts = countBlocksByType(response);
console.log('Block counts:', counts);
// { table: 2, pie_chart: 1, bar_chart: 0, timeseries_chart: 0,
// action: 1, markdown: 3, interactive: 0, alert: 0, code: 0, form: 0 }
if (hasBlockType(response, 'action')) {
console.log('Response includes transaction actions.');
}
if (hasBlockType(response, 'table')) {
console.log(`Response includes ${counts.table} table(s).`);
}
}Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
Complete Example
A full workflow combining multiple helper functions:
import {
Chaos, WALLET_MODEL,
// Response helpers
extractText, extractBlocks, hasRisks, hasBlockers,
// Block extraction
extractTableBlocks, extractTransactionBlocks, extractChartBlocks,
// Search
findTableByTitle, findTransactionsByPrimitive,
// Primitives
extractPrimitives, getPrimitiveTypes, PRIMITIVE_SWAP,
// Table utils
tableToObjects, getTableDimensions,
// Chart utils
getChartData, getChartPercentages, isPieChartBlock,
// Risk utils
getAllWarnings, getAllBlockers, getHighestRiskLevel,
// Stats
countBlocksByType, hasBlocks,
} from '@chaoslabs/ai-sdk';
const chaos = new Chaos({ apiKey: process.env.CHAOS_API_KEY! });
const response = await chaos.chat.responses.create({
model: WALLET_MODEL,
input: [{ type: 'message', role: 'user', content: 'Show my portfolio and suggest optimizations' }],
metadata: {
user_id: 'user-1',
session_id: 'session-1',
wallets: [{ address: '0x...', chain: 'ethereum' }],
},
});
// Overview
console.log(`Status: ${response.status}`);
console.log(`Text: ${extractText(response).slice(0, 200)}...`);
console.log(`Block counts:`, countBlocksByType(response));
// Tables
const portfolioTable = findTableByTitle(response, 'portfolio');
if (portfolioTable) {
const { columns, rows } = getTableDimensions(portfolioTable);
console.log(`Portfolio: ${rows} assets, ${columns} columns`);
const assets = tableToObjects<{ Asset: string; Value: string }>(portfolioTable);
for (const a of assets) console.log(` ${a.Asset}: ${a.Value}`);
}
// Charts
for (const chart of extractChartBlocks(response)) {
if (isPieChartBlock(chart)) {
console.log(`Chart: ${chart.title}`);
for (const item of getChartPercentages(chart)) {
console.log(` ${item.label}: ${item.percentage.toFixed(1)}%`);
}
}
}
// Transactions & risks
const primitiveTypes = getPrimitiveTypes(response);
console.log('Primitive types:', primitiveTypes);
console.log(`Highest risk: ${getHighestRiskLevel(response) ?? 'none'}`);
console.log(`Warnings: ${getAllWarnings(response).length}`);
console.log(`Blockers: ${getAllBlockers(response).length}`);Copy code
Open in Cursor
Open in VS Code
Open in v0
Open in Claude
Open in ChatGPT
Was this helpful?