Response Handling

Updated

The SDK provides top-level helper functions for extracting data from ChatCreateResponse objects. These are exported directly from @chaoslabs/ai-sdk.

extractText

Extract all text content from a response. Concatenates all text-type messages with newlines.

signature.ts
function extractText(response: ChatCreateResponse): string
example.ts
import { Chaos, WALLET_MODEL, extractText } 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: 'What is Aave?' }],
  metadata: { user_id: 'user-1', session_id: 'session-1' },
});
 
const text = extractText(response);
console.log(text);
// "Aave is a decentralized lending protocol..."

extractBlocks

Extract all Block objects from a response. This is an alias for extractBlocksFromMessages.

signature.ts
function extractBlocks(response: ChatCreateResponse): Block[]
[@portabletext/react] Unknown block type "callout", specify a component for it in the `components.types` prop
example.ts
import { extractBlocks } from '@chaoslabs/ai-sdk';
 
const blocks = extractBlocks(response);
console.log(`Response contains ${blocks.length} blocks`);
 
for (const block of blocks) {
  console.log(`  ${block.type}:`, block.type === 'table' ? block.title : '');
}

response.status

The status field on ChatCreateResponse indicates whether the request completed successfully.

ValueMeaning
"completed"The request finished successfully
"failed"The request encountered an error
example.ts
const response = await chaos.chat.responses.create({ ... });
 
if (response.status === 'failed') {
  console.error('Request failed:', response.error?.message);
} else {
  console.log('Success! Messages:', response.messages?.length);
}

hasRisks

Check if a response contains any action blocks with risk levels above low.

signature.ts
function hasRisks(response: ChatCreateResponse): boolean

Returns true if any action block has a risks.level that is not 'low' (i.e., 'medium', 'high', or 'critical').

example.ts
import { hasRisks } from '@chaoslabs/ai-sdk';
 
const response = await chaos.chat.responses.create({ ... });
 
if (hasRisks(response)) {
  console.warn('This transaction has elevated risk. Review before executing.');
}

hasBlockers

Check if a response contains any action blocks with blocking risk levels (high or critical) or explicit blockers.

signature.ts
function hasBlockers(response: ChatCreateResponse): boolean

Returns true if any action block has:

  • risks.level of 'high' or 'critical', OR
  • A non-empty risks.blockers array
example.ts
import { hasBlockers } from '@chaoslabs/ai-sdk';
 
const response = await chaos.chat.responses.create({ ... });
 
if (hasBlockers(response)) {
  console.error('Transaction blocked! Critical risks detected.');
  // Do not proceed with transaction execution
} else {
  // Safe to execute
}

Combining Response Helpers

A typical pattern for processing responses:

full-example.ts
import {
  Chaos, WALLET_MODEL,
  extractText, extractBlocks,
  hasRisks, hasBlockers,
} 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: 'Deposit 1 ETH into Aave' }],
  metadata: {
    user_id: 'user-1',
    session_id: 'session-1',
    wallets: [{ address: '0x...', chain: 'ethereum' }],
  },
});
 
// 1. Check status
if (response.status === 'failed') {
  throw new Error(response.error?.message ?? 'Unknown error');
}
 
// 2. Extract content
const text = extractText(response);
const blocks = extractBlocks(response);
console.log(`Text: ${text}`);
console.log(`Blocks: ${blocks.length}`);
 
// 3. Check risks before executing
if (hasBlockers(response)) {
  console.error('Transaction blocked due to critical risks.');
} else if (hasRisks(response)) {
  console.warn('Elevated risk detected. Proceed with caution.');
} else {
  console.log('Transaction looks safe. Ready to execute.');
}

For more granular block extraction and analysis, see Block Types and Helper Functions.

Was this helpful?