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.

signatures.ts
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[]
FunctionReturnsDescription
extractTableBlocksTableBlock[]All table blocks
extractChartBlocksChartBlock[]All chart blocks (pie, bar, timeseries)
extractTransactionBlocksActionBlock[]All transaction action blocks
extractMarkdownBlocksMarkdownBlock[]All markdown blocks
extractInteractiveBlocksInteractiveBlock[]All interactive prompt blocks
extractInfoBlocksAlertBlock[]All alert blocks
extractCodeBlocksCodeBlock[]All code blocks
extractFormBlocksFormBlock[]All form blocks
example.ts
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`);

Find specific blocks by title or content.

signatures.ts
function findTableByTitle(
  response: ChatCreateResponse,
  title: string
): TableBlock | undefined
 
function findChartByTitle(
  response: ChatCreateResponse,
  title: string
): ChartBlock | undefined
 
function findTransactionsByPrimitive(
  response: ChatCreateResponse,
  primitiveType: string
): ActionBlock[]
FunctionReturnsDescription
findTableByTitleTableBlock | undefinedFirst table whose title contains the search string (case-insensitive)
findChartByTitleChartBlock | undefinedFirst chart whose title contains the search string (case-insensitive)
findTransactionsByPrimitiveActionBlock[]All action blocks containing a primitive of the given type
example.ts
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);

Primitive Extraction

Extract and filter transaction primitives from action blocks.

signatures.ts
function extractPrimitives(response: ChatCreateResponse): Primitive[]
 
function extractPrimitivesByType(
  response: ChatCreateResponse,
  primitiveType: string
): Primitive[]
 
function getPrimitiveTypes(response: ChatCreateResponse): string[]
FunctionReturnsDescription
extractPrimitivesPrimitive[]All primitives from all action blocks
extractPrimitivesByTypePrimitive[]Primitives matching a specific type string
getPrimitiveTypesstring[]Unique primitive type strings in the response
example.ts
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}`);
  }
}

Table Utilities

Work with TableBlock data: convert to objects, extract columns, search rows, and get dimensions.

signatures.ts
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 }
FunctionReturnsDescription
tableToObjects<T>T[]Convert table rows to typed objects using headers as keys
getTableColumnunknown[]Extract all values from a named column
findTableRowunknown[] | undefinedFind the first row where a column matches a value
getTableDimensions{ columns, rows }Get the number of columns and rows
example.ts
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);
  }
}

Chart Utilities

Extract data, totals, and percentages from PieChartBlock charts.

signatures.ts
function getChartData(chart: PieChartBlock): Array<{ label: string; value: number }>
 
function getChartTotal(chart: PieChartBlock): number
 
function getChartPercentages(
  chart: PieChartBlock
): Array<{ label: string; percentage: number }>
FunctionReturnsDescription
getChartDataArray<{ label, value }>Flatten series data into label-value pairs
getChartTotalnumberSum of all chart segment values
getChartPercentagesArray<{ label, percentage }>Each segment as a percentage of the total
[@portabletext/react] Unknown block type "callout", specify a component for it in the `components.types` prop
example.ts
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)}%`);
    }
  }
}

Risk Utilities

Analyze risk data from action blocks across a response.

signatures.ts
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';
FunctionReturnsDescription
getAllWarningsRiskInfoItem[]All warning items from all action blocks
getAllBlockersRiskInfoItem[]All blocker items from all action blocks
getHighestRiskLevelRiskLevel | undefinedThe highest risk level across all action blocks
example.ts
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}`);
}

Block Statistics

Count and check for blocks by type.

signatures.ts
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;
// }
FunctionReturnsDescription
countBlocksByTypeBlockTypeCountsCount of each block type in the response
hasBlocksbooleanWhether the response contains any blocks
hasBlockTypebooleanWhether the response contains a specific block type
example.ts
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).`);
  }
}

Complete Example

A full workflow combining multiple helper functions:

full-example.ts
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}`);
Was this helpful?