Contexts and Workflows

View as MarkdownOpen in Claude

The features in this chapter build on the fundamentals covered earlier. While basic agents handle free-form conversations well, many real-world applications require more structure: guided workflows that ensure certain information is collected, the ability to transfer between different “departments” or personas, recording for compliance, and integration with knowledge bases.

These advanced features transform simple voice agents into sophisticated conversational applications capable of handling complex business processes.

When to Use Contexts

Contexts are the SDK’s answer to a common challenge: how do you ensure a conversation follows a specific path? Regular prompts work well for open-ended conversations, but many business processes require structure — collecting specific information in a specific order, or routing callers through a defined workflow.

Think of contexts as conversation “states” or “modes.” Each context can have its own persona, available functions, and series of steps. The AI automatically manages transitions between contexts and steps based on criteria you define.

Regular PromptsContexts
Free-form conversationsStructured workflows
Simple Q&A agentsMulti-step data collection
Single-purpose tasksWizard-style flows
No defined sequenceBranching conversations
Multiple personas

Use contexts when you need:

  • Guaranteed step completion
  • Controlled navigation
  • Step-specific function access
  • Context-dependent personas
  • Department transfers
  • Isolated conversation segments

Common context patterns:

  • Data collection wizard: Gather customer information step-by-step (name, address, payment)
  • Triage flow: Qualify callers before routing to appropriate department
  • Multi-department support: Sales, Support, and Billing each with their own persona
  • Appointment scheduling: Check availability, select time, confirm details
  • Order processing: Select items, confirm order, process payment

Context Architecture

Understanding how contexts, steps, and navigation work together is essential for building effective workflows.

Key concepts:

  • ContextBuilder: The top-level container that holds all your contexts
  • Context: A distinct conversation mode (like “sales” or “support”), with its own persona and settings
  • Step: A specific point within a context where certain tasks must be completed

The AI automatically tracks which context and step the conversation is in. When step criteria are met, it advances to the next allowed step. When context navigation is permitted and appropriate, it switches contexts entirely.

Diagram showing the hierarchical structure of ContextBuilder, Contexts, and Steps with navigation flow.
Context structure showing contexts, steps, and navigation paths.

How state flows through contexts:

  1. Caller starts in the first step of the default (or specified) context
  2. AI follows the step’s instructions until step_criteria is satisfied
  3. AI chooses from valid_steps to advance within the context
  4. If valid_contexts allows, AI can switch to a different context entirely
  5. When switching contexts, isolated, consolidate, or full_reset settings control what conversation history carries over

Basic Context Example

1from signalwire import AgentBase
2
3class OrderAgent(AgentBase):
4 def __init__(self):
5 super().__init__(name="order-agent")
6 self.add_language("English", "en-US", "rime.spore")
7
8 # Base prompt (required even with contexts)
9 self.prompt_add_section(
10 "Role",
11 "You help customers place orders."
12 )
13
14 # Define contexts after setting base prompt
15 contexts = self.define_contexts()
16
17 # Add a context with steps
18 order = contexts.add_context("default")
19
20 order.add_step("get_item") \
21 .set_text("Ask what item they want to order.") \
22 .set_step_criteria("Customer has specified an item") \
23 .set_valid_steps(["get_quantity"])
24
25 order.add_step("get_quantity") \
26 .set_text("Ask how many they want.") \
27 .set_step_criteria("Customer has specified a quantity") \
28 .set_valid_steps(["confirm"])
29
30 order.add_step("confirm") \
31 .set_text("Confirm the order details and thank them.") \
32 .set_step_criteria("Order has been confirmed")
33
34if __name__ == "__main__":
35 agent = OrderAgent()
36 agent.run()

Compact Step Definition

Steps can be fully configured in a single add_step() call using keyword arguments:

1contexts = self.define_contexts()
2order = contexts.add_context("default")
3
4order.add_step("get_item",
5 task="Ask what item they want to order.",
6 bullets=["Show available items", "Confirm selection"],
7 criteria="Customer has specified an item",
8 functions=["check_inventory"],
9 valid_steps=["get_quantity"]
10)
11
12order.add_step("get_quantity",
13 task="Ask how many they want.",
14 criteria="Customer has specified a quantity",
15 valid_steps=["confirm"]
16)
17
18order.add_step("confirm",
19 task="Confirm the order details and thank them.",
20 criteria="Order has been confirmed"
21)

The task parameter creates a POM section titled “Task” with the given text. The bullets, criteria, functions, and valid_steps parameters map to add_bullets(), set_step_criteria(), set_functions(), and set_valid_steps() respectively. You can still use the method-chaining API when you need more control.

Step Configuration

set_text()

Simple text prompt for the step:

LanguageSyntax
Pythonstep.set_text("What item would you like to order?")
TypeScriptstep.setText('What item would you like to order?')

add_section() / add_bullets()

POM-style structured prompts:

LanguageSyntax
Pythonstep.add_section("Task", "Collect customer info").add_bullets("Required", ["Full name", "Phone"])
TypeScriptstep.addSection('Task', 'Collect customer info').addBullets('Required', ['Full name', 'Phone'])

set_step_criteria()

Define when the step is complete:

LanguageSyntax
Pythonstep.set_step_criteria("Customer has provided their full name and phone number")
TypeScriptstep.setStepCriteria('Customer has provided their full name and phone number')

set_valid_steps()

Control step navigation:

LanguageSyntax
Pythonstep.set_valid_steps(["confirm", "cancel"])
TypeScriptstep.setValidSteps(['confirm', 'cancel'])

set_functions()

Restrict available functions per step:

LanguageSyntax
Pythonstep.set_functions(["check_inventory", "get_price"])
TypeScriptstep.setFunctions(['check_inventory', 'get_price'])

set_valid_contexts()

Allow navigation to other contexts:

LanguageSyntax
Pythonstep.set_valid_contexts(["support", "manager"])
TypeScriptstep.setValidContexts(['support', 'manager'])

Step Behavior Flags

Control how steps transition without relying on criteria evaluation:

1# End the conversation after this step (cannot combine with valid_steps)
2step.set_end(True)
3
4# Skip waiting for user input — proceed immediately
5step.set_skip_user_turn(True)
6
7# Auto-advance to the next step without evaluating criteria
8step.set_skip_to_next_step(True)

These flags are useful for non-interactive steps like announcements, automated transitions, or terminal farewell steps.

Understanding Step Criteria

Step criteria tell the AI when a step is “complete” and it’s time to move on. Writing good criteria is crucial — too vague and the AI may advance prematurely; too strict and the conversation may get stuck.

Good criteria are:

  • Specific and measurable
  • Phrased as completion conditions
  • Focused on what information has been collected

Examples of well-written criteria:

1# Good: Specific, measurable
2.set_step_criteria("Customer has provided their full name and email address")
3
4# Good: Clear completion condition
5.set_step_criteria("Customer has selected a product and confirmed the quantity")
6
7# Good: Explicit confirmation
8.set_step_criteria("Customer has verbally confirmed the order total")

Problematic criteria to avoid:

1# Bad: Too vague
2.set_step_criteria("Customer is ready")
3
4# Bad: Subjective
5.set_step_criteria("Customer seems satisfied")
6
7# Bad: No clear completion point
8.set_step_criteria("Help the customer")

Context Configuration

set_isolated()

Truncate conversation history when entering:

LanguageSyntax
Pythoncontext.set_isolated(True)
TypeScriptcontext.setIsolated(true)

set_system_prompt()

New system prompt when entering context:

LanguageSyntax
Pythoncontext.set_system_prompt("You are now a technical support specialist.")
TypeScriptcontext.setSystemPrompt('You are now a technical support specialist.')

set_user_prompt()

Inject a user message when entering:

LanguageSyntax
Pythoncontext.set_user_prompt("I need help with a technical issue.")
TypeScriptcontext.setUserPrompt('I need help with a technical issue.')

set_consolidate()

Summarize previous conversation when switching:

LanguageSyntax
Pythoncontext.set_consolidate(True)
TypeScriptcontext.setConsolidate(true)

set_full_reset()

Completely reset conversation state:

LanguageSyntax
Pythoncontext.set_full_reset(True)
TypeScriptcontext.setFullReset(true)

add_enter_filler() / add_exit_filler()

Add transition phrases:

1context.add_enter_filler("en-US", [
2 "Let me connect you with our support team...",
3 "Transferring you to a specialist..."
4])
5
6context.add_exit_filler("en-US", [
7 "Returning you to the main menu...",
8 "Back to the sales department..."
9])

Multi-Context Example

1from signalwire import AgentBase
2
3class MultiDepartmentAgent(AgentBase):
4 def __init__(self):
5 super().__init__(name="multi-dept-agent")
6 self.add_language("English-Sales", "en-US", "rime.spore")
7 self.add_language("English-Support", "en-US", "rime.cove")
8 self.add_language("English-Manager", "en-US", "rime.marsh")
9
10 self.prompt_add_section(
11 "Instructions",
12 "Guide customers through sales or transfer to appropriate departments."
13 )
14
15 contexts = self.define_contexts()
16
17 # Sales context
18 sales = contexts.add_context("sales") \
19 .set_isolated(True) \
20 .add_section("Role", "You are Alex, a sales representative.")
21
22 sales.add_step("qualify") \
23 .add_section("Task", "Determine customer needs") \
24 .set_step_criteria("Customer needs are understood") \
25 .set_valid_steps(["recommend"]) \
26 .set_valid_contexts(["support", "manager"])
27
28 sales.add_step("recommend") \
29 .add_section("Task", "Make product recommendations") \
30 .set_step_criteria("Recommendation provided") \
31 .set_valid_contexts(["support", "manager"])
32
33 # Support context
34 support = contexts.add_context("support") \
35 .set_isolated(True) \
36 .add_section("Role", "You are Sam, technical support.") \
37 .add_enter_filler("en-US", [
38 "Connecting you with technical support...",
39 "Let me transfer you to our tech team..."
40 ])
41
42 support.add_step("assist") \
43 .add_section("Task", "Help with technical questions") \
44 .set_step_criteria("Technical issue resolved") \
45 .set_valid_contexts(["sales", "manager"])
46
47 # Manager context
48 manager = contexts.add_context("manager") \
49 .set_isolated(True) \
50 .add_section("Role", "You are Morgan, the store manager.") \
51 .add_enter_filler("en-US", [
52 "Let me get the manager for you...",
53 "One moment, connecting you with management..."
54 ])
55
56 manager.add_step("escalate") \
57 .add_section("Task", "Handle escalated issues") \
58 .set_step_criteria("Issue resolved by manager") \
59 .set_valid_contexts(["sales", "support"])
60
61if __name__ == "__main__":
62 agent = MultiDepartmentAgent()
63 agent.run()

Within Context (Steps)

  • set_valid_steps(["next"]) - Go to next sequential step
  • set_valid_steps(["step_name"]) - Go to specific step
  • set_valid_steps(["a", "b"]) - Multiple options

Context-Level Valid Steps

You can set valid_steps at the context level to apply default step navigation for all steps in the context. Step-level valid_steps overrides context-level when set.

1contexts = self.define_contexts()
2order = contexts.add_context("default")
3
4# All steps in this context can navigate to "cancel" by default
5order.set_valid_steps(["next", "cancel"])
6
7order.add_step("get_item",
8 task="Ask what item they want to order.",
9 criteria="Customer has specified an item"
10)
11order.add_step("get_quantity",
12 task="Ask how many they want.",
13 criteria="Customer has specified a quantity"
14)
15order.add_step("cancel",
16 task="Cancel the order and apologize."
17)

Between Contexts

  • set_valid_contexts(["other_context"]) - Allow context switch
  • AI calls change_context("context_name") automatically
  • Enter/exit fillers provide smooth transitions

Context Entry Behavior

  • isolated=True - Clear conversation history
  • consolidate=True - Summarize previous conversation
  • full_reset=True - Complete prompt replacement

Context Manipulation

After defining contexts and steps, you can retrieve, modify, reorder, or remove them programmatically.

Retrieving Contexts and Steps

1contexts = self.define_contexts()
2
3# Build your contexts...
4order = contexts.add_context("default")
5order.add_step("greeting", task="Greet the caller.")
6
7# Later, retrieve and modify
8ctx = contexts.get_context("default")
9step = ctx.get_step("greeting")
10step.clear_sections()
11step.set_text("Welcome! How can I help you today?")

Removing and Reordering Steps

1# Remove a step entirely
2ctx.remove_step("obsolete_step")
3
4# Move a step to a new position (0-indexed)
5ctx.move_step("confirm", 0) # Move "confirm" to the first position

Clearing Step Content

Use clear_sections() to remove all POM sections and text from a step so you can repopulate it:

1step = ctx.get_step("collect_info")
2step.clear_sections()
3step.add_section("Task", "Updated instructions for collecting info.")

Gather Info Steps

The gather info system lets you define structured question sequences within a step. Questions are presented one at a time via the SignalWire platform’s built-in gather mechanism, producing zero tool_call/tool_result entries in the LLM conversation history. This keeps the history clean and focused.

Basic Gather Info

1from signalwire import AgentBase
2
3class IntakeAgent(AgentBase):
4 def __init__(self):
5 super().__init__(name="intake-agent")
6 self.add_language("English", "en-US", "rime.spore")
7
8 self.prompt_add_section(
9 "Role",
10 "You collect patient intake information."
11 )
12
13 contexts = self.define_contexts()
14 ctx = contexts.add_context("default")
15
16 intake = ctx.add_step("intake")
17 intake.set_gather_info(
18 output_key="patient_info",
19 completion_action="next_step",
20 prompt="You are collecting patient information. Be friendly and professional."
21 )
22 intake.add_gather_question(
23 key="full_name",
24 question="What is your full name?",
25 type="string",
26 confirm=True
27 )
28 intake.add_gather_question(
29 key="dob",
30 question="What is your date of birth?",
31 type="string"
32 )
33 intake.add_gather_question(
34 key="reason",
35 question="What is the reason for your visit today?",
36 type="string",
37 prompt="Be empathetic when asking about the reason for the visit."
38 )
39 intake.set_valid_steps(["summary"])
40
41 ctx.add_step("summary",
42 task="Summarize the collected information and confirm with the patient.",
43 criteria="Patient has confirmed the information is correct"
44 )
45
46if __name__ == "__main__":
47 agent = IntakeAgent()
48 agent.run()

Gather Info Parameters

ParameterDescription
output_keyKey in global_data where answers are stored (default: top-level)
completion_actionSet to "next_step" to auto-advance when all questions are answered
promptPreamble text giving the AI personality/context for the questions

Gather Question Parameters

ParameterTypeDefaultDescription
keystrrequiredKey name for storing the answer in global_data
questionstrrequiredThe question text to ask
typestr"string"JSON schema type for the answer
confirmboolFalseRequire confirmation before accepting
promptstrNoneExtra instruction text for this specific question
functionsList[str]NoneAdditional functions visible during this question

When to Use Gather Info vs Regular Steps

FeatureRegular StepsGather Info Steps
History impactAdds tool calls to historyZero history entries
ControlFull AI flexibilityStructured one-at-a-time
Best forOpen-ended conversationForm-like data collection
ConfirmationManual via criteriaBuilt-in confirm flag
Auto-advanceVia valid_stepsVia completion_action

Validation Rules

The ContextBuilder validates your configuration:

  • Single context must be named “default”
  • Every context must have at least one step
  • valid_steps must reference existing steps (or “next”)
  • valid_contexts must reference existing contexts
  • Cannot mix set_text() with add_section() on same step
  • Cannot mix set_prompt() with add_section() on same context

Step and Context Methods Summary

MethodLevelPurpose
set_text()StepSimple text prompt
add_section()BothPOM-style section
add_bullets()BothBulleted list section
set_step_criteria()StepCompletion criteria
set_functions()StepRestrict available functions
set_valid_steps()BothAllowed step navigation (context-level applies to all steps)
set_valid_contexts()BothAllowed context navigation
set_end()StepEnd conversation after this step
set_skip_user_turn()StepSkip waiting for user input
set_skip_to_next_step()StepAuto-advance to next step
clear_sections()StepRemove all sections/text for repopulation
set_gather_info()StepEnable structured question gathering
add_gather_question()StepAdd a question to gather info
set_isolated()ContextClear history on entry
set_consolidate()ContextSummarize on entry
set_full_reset()ContextComplete reset on entry
set_system_prompt()ContextNew system prompt
set_user_prompt()ContextInject user message
add_enter_filler()ContextEntry transition phrases
add_exit_filler()ContextExit transition phrases
get_step()ContextRetrieve a step by name
remove_step()ContextRemove a step
move_step()ContextReorder a step
get_context()ContextBuilderRetrieve a context by name

Context Switching Behavior

When the AI switches between contexts, several things can happen depending on your configuration. Understanding these options helps you create smooth transitions.

Isolated Contexts

When isolated=True, the conversation history is cleared when entering the context. This is useful when:

  • You want a clean slate for a new department
  • Previous context shouldn’t influence the new persona
  • You’re implementing strict separation between workflow segments
1support = contexts.add_context("support") \
2 .set_isolated(True) # Fresh start when entering support

The caller won’t notice — the AI simply starts fresh with no memory of the previous context.

Consolidated Contexts

When consolidate=True, the AI summarizes the previous conversation before switching. This preserves important information without carrying over the full history:

1billing = contexts.add_context("billing") \
2 .set_consolidate(True) # Summarize previous conversation

The summary includes key facts and decisions, giving the new context awareness of what happened without the full transcript.

Full Reset Contexts

full_reset=True goes further than isolation — it completely replaces the system prompt and clears all state:

1escalation = contexts.add_context("escalation") \
2 .set_full_reset(True) # Complete prompt replacement

Use this when the new context needs to behave as if it were a completely different agent.

Combining with Enter/Exit Fillers

Fillers provide audio feedback during context switches, making transitions feel natural:

1support = contexts.add_context("support") \
2 .set_isolated(True) \
3 .add_enter_filler("en-US", [
4 "Let me transfer you to technical support.",
5 "One moment while I connect you with a specialist."
6 ]) \
7 .add_exit_filler("en-US", [
8 "Returning you to the main menu.",
9 "Transferring you back."
10 ])

The AI randomly selects from the filler options, providing variety in the transitions.

Debugging Context Flows

When contexts don’t behave as expected, use these debugging strategies:

  1. Check step criteria: If stuck on a step, the criteria may be too strict. Temporarily loosen them to verify the flow works.

  2. Verify navigation paths: Ensure valid_steps and valid_contexts form a complete graph. Every step should have somewhere to go (unless it’s a terminal step).

  3. Test with swaig-test: The testing tool shows context configuration in the SWML output:

$swaig-test your_agent.py --dump-swml | grep -A 50 "contexts"
  1. Add logging in handlers: If you have SWAIG functions, log when they’re called to trace the conversation flow.

  2. Watch for validation errors: The ContextBuilder validates your configuration at runtime. Check logs for validation failures.

Best Practices

DO:

  • Set clear step_criteria for each step
  • Use isolated=True for persona changes
  • Add enter_fillers for smooth transitions
  • Define valid_contexts to enable department transfers
  • Test navigation paths thoroughly
  • Provide escape routes from every step (avoid dead ends)
  • Use consolidate=True when context needs awareness of previous conversation

DON’T:

  • Create circular navigation without exit paths
  • Skip setting a base prompt before define_contexts()
  • Mix set_text() with add_section() on the same step
  • Forget to validate step/context references
  • Use full_reset unless you truly need a complete persona change
  • Make criteria too vague or too strict