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

1import { ContextBuilder } from '@signalwire/sdk';
2
3const builder = new ContextBuilder();
4const order = builder.addContext('default');
5
6order.addStep('get_item')
7 .setText('Ask what item they want to order.')
8 .setStepCriteria('Customer has specified an item')
9 .setValidSteps(['get_quantity']);
10
11order.addStep('get_quantity')
12 .setText('Ask how many they want.')
13 .setStepCriteria('Customer has specified a quantity')
14 .setValidSteps(['confirm']);
15
16order.addStep('confirm')
17 .setText('Confirm the order details and thank them.')
18 .setStepCriteria('Order has been confirmed')
19 .setEnd(true);
20
21const swml = builder.toDict();
22console.log(JSON.stringify(swml, null, 2));

Multiple contexts

1import { ContextBuilder } from '@signalwire/sdk';
2
3const builder = new ContextBuilder();
4
5// Main menu
6const main = builder.addContext('default');
7main.addStep('menu')
8 .setText('Ask whether they need sales, support, or billing help.')
9 .setFunctions('none')
10 .setValidContexts(['sales', 'support']);
11
12// Sales context
13const sales = builder.addContext('sales');
14sales.setSystemPrompt('You are a friendly sales representative.');
15sales.addStep('qualify')
16 .setText('Understand what product the caller is interested in.')
17 .setFunctions(['check_inventory', 'get_pricing'])
18 .setValidSteps(['close']);
19sales.addStep('close')
20 .setText('Close the sale or schedule a follow-up.')
21 .setValidContexts(['default']);
22
23// Support context
24const support = builder.addContext('support');
25support.setSystemPrompt('You are a patient support engineer.');
26support.addStep('diagnose')
27 .setText('Understand the customer\'s issue.')
28 .setFunctions(['lookup_account', 'check_status'])
29 .setValidSteps(['resolve']);
30support.addStep('resolve')
31 .setText('Resolve the issue or escalate.')
32 .setFunctions(['create_ticket', 'transfer_call'])
33 .setValidContexts(['default']);