ContextBuilder

View as MarkdownOpen in Claude

ContextBuilder is the top-level container for defining structured conversation workflows. It holds one or more Context objects, each containing a sequence of Step objects. Use it when your agent needs guided, multi-step conversations instead of free-form prompting.

Access the builder by calling defineContexts() on an AgentBase instance. The builder validates the entire context tree when the SWML document is rendered.

You rarely create a ContextBuilder directly. Call defineContexts() inside your agent class, which creates the builder and wires it into SWML generation automatically.

Methods


Limits

LimitValue
Maximum contexts per builder50
Maximum steps per context100

Examples

Single context with sequential steps

import { ContextBuilder } from '@signalwire/sdk';
const builder = new ContextBuilder();
const order = builder.addContext('default');
order.addStep('get_item')
.setText('Ask what item they want to order.')
.setStepCriteria('Customer has specified an item')
.setValidSteps(['get_quantity']);
order.addStep('get_quantity')
.setText('Ask how many they want.')
.setStepCriteria('Customer has specified a quantity')
.setValidSteps(['confirm']);
order.addStep('confirm')
.setText('Confirm the order details and thank them.')
.setStepCriteria('Order has been confirmed')
.setEnd(true);
const swml = builder.toDict();
console.log(JSON.stringify(swml, null, 2));

Multiple contexts

import { ContextBuilder } from '@signalwire/sdk';
const builder = new ContextBuilder();
// Main menu
const main = builder.addContext('default');
main.addStep('menu')
.setText('Ask whether they need sales, support, or billing help.')
.setFunctions('none')
.setValidContexts(['sales', 'support']);
// Sales context
const sales = builder.addContext('sales');
sales.setSystemPrompt('You are a friendly sales representative.');
sales.addStep('qualify')
.setText('Understand what product the caller is interested in.')
.setFunctions(['check_inventory', 'get_pricing'])
.setValidSteps(['close']);
sales.addStep('close')
.setText('Close the sale or schedule a follow-up.')
.setValidContexts(['default']);
// Support context
const support = builder.addContext('support');
support.setSystemPrompt('You are a patient support engineer.');
support.addStep('diagnose')
.setText('Understand the customer\'s issue.')
.setFunctions(['lookup_account', 'check_status'])
.setValidSteps(['resolve']);
support.addStep('resolve')
.setText('Resolve the issue or escalate.')
.setFunctions(['create_ticket', 'transfer_call'])
.setValidContexts(['default']);