@signalwire/sdk 3.7.2 → 3.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +201 -0
- package/README.md +1 -0
- package/dist/AgentBase.d.ts +107 -2
- package/dist/AgentBase.js +259 -13
- package/dist/AgentBase.js.map +1 -1
- package/dist/AiEvents.d.ts +70 -0
- package/dist/AiEvents.js +94 -0
- package/dist/AiEvents.js.map +1 -0
- package/dist/ContextBuilder.d.ts +215 -14
- package/dist/ContextBuilder.js +441 -14
- package/dist/ContextBuilder.js.map +1 -1
- package/dist/FunctionResult.d.ts +146 -1
- package/dist/FunctionResult.js +188 -2
- package/dist/FunctionResult.js.map +1 -1
- package/dist/PostPrompt.d.ts +19 -0
- package/dist/PostPrompt.js +43 -0
- package/dist/PostPrompt.js.map +1 -1
- package/dist/SWMLService.d.ts +97 -1
- package/dist/SWMLService.js +129 -2
- package/dist/SWMLService.js.map +1 -1
- package/dist/SemanticGate.d.ts +61 -1
- package/dist/SemanticGate.js +108 -15
- package/dist/SemanticGate.js.map +1 -1
- package/dist/SwaigFunction.d.ts +85 -9
- package/dist/SwaigFunction.js +214 -58
- package/dist/SwaigFunction.js.map +1 -1
- package/dist/ToolMiddleware.d.ts +82 -0
- package/dist/ToolMiddleware.js +131 -0
- package/dist/ToolMiddleware.js.map +1 -0
- package/dist/TypeInference.d.ts +1 -1
- package/dist/TypeInference.js.map +1 -1
- package/dist/cli/tsdocs/api-index.json +1 -1
- package/dist/cli/tsdocs/topics.js +24 -4
- package/dist/cli/tsdocs/topics.js.map +1 -1
- package/dist/index.d.ts +22 -8
- package/dist/index.js +15 -5
- package/dist/index.js.map +1 -1
- package/dist/llms.txt +1 -0
- package/dist/patterns/Proposal.d.ts +148 -0
- package/dist/patterns/Proposal.js +214 -0
- package/dist/patterns/Proposal.js.map +1 -0
- package/dist/patterns/RequestList.d.ts +138 -0
- package/dist/patterns/RequestList.js +171 -0
- package/dist/patterns/RequestList.js.map +1 -0
- package/dist/skills/SkillBase.d.ts +24 -1
- package/dist/skills/SkillBase.js +12 -1
- package/dist/skills/SkillBase.js.map +1 -1
- package/dist/speech/numbers.d.ts +66 -0
- package/dist/speech/numbers.js +281 -0
- package/dist/speech/numbers.js.map +1 -0
- package/dist/speech/spelling.d.ts +71 -0
- package/dist/speech/spelling.js +294 -0
- package/dist/speech/spelling.js.map +1 -0
- package/dist/testing/CallSimulator.d.ts +391 -0
- package/dist/testing/CallSimulator.js +966 -0
- package/dist/testing/CallSimulator.js.map +1 -0
- package/docs/agent-guide.md +2 -2
- package/docs/api-reference.md +279 -22
- package/docs/architecture.md +8 -4
- package/docs/cli-guide.md +2 -0
- package/docs/contexts-guide.md +75 -4
- package/docs/conversation_patterns.md +257 -0
- package/docs/mcp_integration.md +1 -1
- package/docs/pgi_agent_guide.md +5 -0
- package/docs/programmatically_governed_inference.md +2 -2
- package/docs/swaig-reference.md +98 -6
- package/package.json +1 -1
package/docs/architecture.md
CHANGED
|
@@ -534,14 +534,18 @@ The third argument is the agent the request was configured on: the per-request c
|
|
|
534
534
|
Handler returns:
|
|
535
535
|
|
|
|
536
536
|
|-- FunctionResult --> result.toDict()
|
|
537
|
-
|-- { response
|
|
538
|
-
|--
|
|
537
|
+
|-- { response } or { action } --> sent as it is
|
|
538
|
+
|-- any other object --> { response: JSON of the object }; {} -> the outcome is unknown
|
|
539
|
+
|-- undefined or null --> FunctionResult("Function executed successfully").toDict()
|
|
539
540
|
|-- anything else (a string) --> FunctionResult(String(value)).toDict()
|
|
540
|
-
|-- throws
|
|
541
|
+
|-- throws ToolRefusal --> its tool_result and tool_prompt
|
|
542
|
+
|-- throws anything else --> the tool's onError hook, then the agent's onError hook;
|
|
541
543
|
a FunctionResult either returns is sent. Otherwise
|
|
542
|
-
|
|
544
|
+
errorMessage, or toolErrorResult(name): the outcome is unknown
|
|
543
545
|
```
|
|
544
546
|
|
|
547
|
+
The tool middleware runs around this: the resend dedupe, the agent's middleware (`addToolMiddleware()`), then the tool's own, with the same rules for what a middleware returns.
|
|
548
|
+
|
|
545
549
|
`FunctionResult.toDict()` produces an object like this one:
|
|
546
550
|
|
|
547
551
|
```json
|
package/docs/cli-guide.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
`swaig-test` loads an agent file and lets you inspect its SWML, list its SWAIG functions, and call one, without a phone call or a deployment.
|
|
4
4
|
|
|
5
|
+
To test a whole call flow, such as a confirmation across steps, rather than one tool call, use `CallSimulator`; see [Conversation Patterns](conversation_patterns.md#testing-a-call-flow).
|
|
6
|
+
|
|
5
7
|
---
|
|
6
8
|
|
|
7
9
|
## Table of Contents
|
package/docs/contexts-guide.md
CHANGED
|
@@ -222,6 +222,29 @@ Help the customer with their billing inquiry.
|
|
|
222
222
|
- Offer to escalate if needed
|
|
223
223
|
```
|
|
224
224
|
|
|
225
|
+
### Variables in Step Text
|
|
226
|
+
|
|
227
|
+
The platform expands a step's variables, such as `${global_data.order_total}`, when the step is entered. Releases that have re-expansion rewrite the text in place before a request when a value it reads has changed (see [Conversation History Between Steps](#conversation-history-between-steps)); on earlier releases, and with a realtime model, a later `updateGlobalData()` doesn't change text the model already has. To show the new value there, return `FunctionResult.refreshStep()` with the current step's name after the update. Entering the step starts it over, and its `history` mode applies again.
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
import { FunctionResult } from '@signalwire/sdk';
|
|
231
|
+
|
|
232
|
+
const result = new FunctionResult('Added the drink.')
|
|
233
|
+
.updateGlobalData({ order_total: '$14.50' })
|
|
234
|
+
.refreshStep('take_order');
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
### Expected Answers
|
|
238
|
+
|
|
239
|
+
When a step asks for a number with a known length, such as a ZIP code or a PIN, tell the recognizer how many digits to expect. It ends its wait for the number once the caller has said that many. Pass the exact count, or `minDigits` and `maxDigits` for a range, each from 1 to 64. The step emits it as `expected_answer`, which needs a platform release that has it.
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
ctx.addStep('get_zip').setText("Ask for the caller's ZIP code.").setExpectedAnswer(5);
|
|
243
|
+
ctx.addStep('get_pin').setText('Ask for the PIN.').setExpectedAnswer(undefined, { minDigits: 4, maxDigits: 6 });
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
A gather question takes its own, which replaces the step's while that question is asked: see [Expected Digits](#expected-digits). The exported `expectedAnswer()` function builds one, `{ digits: 5 }` or `{ min_digits: 4, max_digits: 6 }`, and checks it; an invalid count or shape throws.
|
|
247
|
+
|
|
225
248
|
### Managing Steps
|
|
226
249
|
|
|
227
250
|
These methods find, remove, reorder and clear steps:
|
|
@@ -334,6 +357,15 @@ A later step that leaves out `setFunctions()` therefore keeps the tools of the s
|
|
|
334
357
|
|
|
335
358
|
The SDK checks every name in a `functions` list, and in each gather question's `functions`, against the agent's registered tools. `validate()` throws for a name that isn't a registered tool or one of the reserved native tools.
|
|
336
359
|
|
|
360
|
+
`ContextBuilder.stepsOffering(name)` returns the `[context, step]` pairs whose function list, or a gather question's, names a tool. The functions a step without `setFunctions()` inherits from the step before it aren't counted, since they depend on how the caller got there; its gather questions' own function lists are. When every step lists its functions and none lists a registered tool, rendering the SWML logs a `tool_offered_by_no_step` warning for it, once: the model never gets that tool unless a function result turns it on with `toggleFunctions()`.
|
|
361
|
+
|
|
362
|
+
Name only a step's own tools in what the model reads in that step. When a step lists its functions, rendering also logs a `tool_named_but_not_offered` warning, once each, for a registered tool named in the step's text, its criteria, its context's prompt (which goes before every step's text), a gather question, or a gate's output on one of its tools, when the step doesn't offer it. A name with an underscore counts anywhere; a one-word name counts only in backticks or before "(". `namedTools(text, tools)` finds the names. Tool results are built at run time, so check those in tests with `new CallSimulator(agent, { checkToolMentions: true })`.
|
|
363
|
+
|
|
364
|
+
```typescript
|
|
365
|
+
const builder = agent.defineContexts();
|
|
366
|
+
console.log(builder.stepsOffering('place_order')); // e.g. [['default', 'confirm']]
|
|
367
|
+
```
|
|
368
|
+
|
|
337
369
|
---
|
|
338
370
|
|
|
339
371
|
## End States
|
|
@@ -387,8 +419,37 @@ The modes are these:
|
|
|
387
419
|
- `default`: hide earlier step instructions, and keep the dialogue. This is the behavior when `history` isn't set.
|
|
388
420
|
- `hide`: hide earlier instructions and the earlier dialogue. A `${step_history.*}` reference in this step's text brings back what you choose.
|
|
389
421
|
- `isolate`: like `hide`, but only while the agent is in this step. When the step is left, the earlier dialogue returns and the step's own turns stay; the earlier instructions stay cleared, and what an earlier `hide` step hid stays hidden. Entering the step again isolates it again. Use it for a step that must see nothing else, such as a confirmation read-back. A platform without `isolate` treats it as `default`.
|
|
422
|
+
- `spoken`: hide earlier instructions, and take every earlier tool call, tool result and turn-scoped system note (tool prompts, `ai-msg` injections, a gather's preamble) out for the rest of the call, while every spoken turn stays, the caller's and the agent's. A platform without `spoken` treats it as `default`.
|
|
390
423
|
|
|
391
|
-
`Context.setHistory()` sets the default for every step in the context, and a step's own `setHistory()` overrides it. Any other value throws.
|
|
424
|
+
`Context.setHistory()` sets the default for every step in the context, and a step's own `setHistory()` overrides it. Any other value throws. See [Conversation History Between Steps](#conversation-history-between-steps) for when each mode applies and what it keeps.
|
|
425
|
+
|
|
426
|
+
### Conversation History Between Steps
|
|
427
|
+
|
|
428
|
+
The mode applies when the step's instructions are injected, before the next request to the model. For a tool whose result changed the step, that's the follow-up request right after the result, so the mode covers everything before the exchange that triggered the change.
|
|
429
|
+
|
|
430
|
+
| Mode | Earlier step instructions | Earlier tool calls and results | Earlier spoken turns |
|
|
431
|
+
|---|---|---|---|
|
|
432
|
+
| `keep` | Kept | Kept | Kept |
|
|
433
|
+
| `default` (when unset) | Cleared | Kept | Kept |
|
|
434
|
+
| `spoken` | Cleared | Gone for the rest of the call | Kept |
|
|
435
|
+
| `hide` | Cleared | Gone for the rest of the call | Gone for the rest of the call |
|
|
436
|
+
| `isolate` | Cleared | Gone while in the step | Gone while in the step |
|
|
437
|
+
|
|
438
|
+
An end step, or one with a reset, takes no history pass: what the model saw stays as it was, and what an `isolate` step hid comes back. A reset step runs its reset in place of its text.
|
|
439
|
+
|
|
440
|
+
`spoken`, `hide` and `isolate` also remove the turn-scoped system notes: tool prompts, `ai-msg` injections and a gather's preamble. All three keep the exchange that entered the step, as the step's start: the call whose action changed the step, its result, notes and `say`, and any caller words stored before the step was injected. The protection covers only the step it entered: after that the exchange is an ordinary entry, which each later step treats by its own mode. An action with `post_process` runs after the model's reply to its result, and its change keeps the call and everything stored from it on: the result and notes, the reply, and the caller's words stored meanwhile. A change by `next_step` keeps nothing. Platform releases before this keep nothing under `hide` and `isolate`, and nothing of a `post_process` change. An agent turn that spoke and called a tool keeps its words under `spoken`. `say` actions are spoken turns. Semantic gates judge the same turns the model sees, so `hide` takes the caller's earlier words from the gates as well, and `spoken` keeps them. A platform release without `isolate` or `spoken` treats the value as `default`.
|
|
441
|
+
|
|
442
|
+
A consolidation's summary stays under `hide` and `spoken`, where it was added; `isolate` hides it while the step lasts. That's the summary the platform writes when the conversation nears the model's context limit, and the one `consolidate` writes on a step's or context's reset or a context switch. Consolidation and the sliding window keep the entries in force: the current step's instructions, with its context's prompt, and during a gather its current question and preamble.
|
|
443
|
+
|
|
444
|
+
On platform releases that have it, the step's instructions are expanded again before a request when a value its text reads has changed, such as global data a tool set. The entry is rewritten in place, and no history mode runs, since the step hasn't changed. An end step, a gather question and a realtime model keep the text as it went in.
|
|
445
|
+
|
|
446
|
+
Choose by what must survive between stages:
|
|
447
|
+
|
|
448
|
+
- **`spoken`** at a stage boundary where the caller's earlier requests must stay but the finished stage's lookups shouldn't. A model that sees old tool results tends to call tools the current step doesn't offer.
|
|
449
|
+
- **`isolate`** on a confirm step, so the read-back is all the model has, with the earlier conversation back once the step is left.
|
|
450
|
+
- **`hide`** only where earlier talk must never come back.
|
|
451
|
+
|
|
452
|
+
What the next stage needs from the last one belongs in `global_data`, shown in the step's text as `${global_data.name}`, not in a tool result the next stage was never meant to see. `${step_history.prev.summary}`, `${step_history.prev.dialog}` and `${step_history.all.dialog}` in a step's text bring back a summary or the transcript of earlier steps under any mode. In a test, `CallSimulator.modelView()` shows what the model gets after each step's mode.
|
|
392
453
|
|
|
393
454
|
---
|
|
394
455
|
|
|
@@ -444,7 +505,7 @@ While a question is asked, the platform deactivates the step's other functions.
|
|
|
444
505
|
|---|---|---|---|
|
|
445
506
|
| `outputKey` | `string` | none | Key in global data that holds the answers. Without it, each answer is stored at the top level. |
|
|
446
507
|
| `completionAction` | `string` | none | Where to go when every question is answered: `'next_step'` for the following step, or the name of a step in the same context. Without it, the step returns to its normal text. |
|
|
447
|
-
| `prompt` | `string` | none |
|
|
508
|
+
| `prompt` | `string` | none | Preamble sent with every question, as a system message ahead of the question's own; each copy replaces the one before. Under the `keep` history mode it's sent with the first question only, and that copy stays. |
|
|
448
509
|
| `isolated` | `boolean` | `false` | Default for every question. When `true`, a question is asked with the other questions and answers hidden from the model, so it must ask rather than work out the answer from an earlier one. The hidden turns stay in the call log. |
|
|
449
510
|
|
|
450
511
|
`validate()` throws when `completionAction` is `'next_step'` on the last step of a context, or names a step that isn't in the context.
|
|
@@ -462,6 +523,16 @@ While a question is asked, the platform deactivates the step's other functions.
|
|
|
462
523
|
| `prompt` | `string` | none | Extra instruction for this question. |
|
|
463
524
|
| `functions` | `string[]` | none | Functions available during this question only. |
|
|
464
525
|
| `isolated` | `boolean` | inherits the gather's setting | `true` hides the other questions and answers while this one is asked. `false` keeps them visible, even in an isolated gather. |
|
|
526
|
+
| `expectedAnswer` | `ExpectedAnswer` | none | The digits the recognizer expects while this question is asked, `{ digits }` or `{ min_digits, max_digits }`. See [Expected Digits](#expected-digits). |
|
|
527
|
+
|
|
528
|
+
#### Expected Digits
|
|
529
|
+
|
|
530
|
+
A question whose answer is a number of known length can tell the recognizer how many digits to expect, with `expectedAnswer`. It applies while that question is asked, in place of the step's `setExpectedAnswer()`.
|
|
531
|
+
|
|
532
|
+
```typescript
|
|
533
|
+
step.setGatherInfo({ outputKey: 'address' });
|
|
534
|
+
step.addGatherQuestion({ key: 'zip', question: 'What is your ZIP code?', expectedAnswer: { digits: 5 } });
|
|
535
|
+
```
|
|
465
536
|
|
|
466
537
|
### GatherInfo Serialization
|
|
467
538
|
|
|
@@ -554,7 +625,7 @@ These settings control what happens to the conversation history when the convers
|
|
|
554
625
|
|
|
555
626
|
### `setIsolated()`
|
|
556
627
|
|
|
557
|
-
`setIsolated(true)` clears the conversation history when the conversation enters the context through `change_context
|
|
628
|
+
`setIsolated(true)` clears the conversation history when the conversation enters the context through `change_context`: the platform drops every entry but the first, the base system prompt. The model starts with the base prompt and the context's step instructions only:
|
|
558
629
|
|
|
559
630
|
<!-- snippet: no-run illustrative fragment: references the assumed `cb` from the page prelude (declared type-only in the shared snippet-setup), not a standalone program -->
|
|
560
631
|
```typescript
|
|
@@ -582,7 +653,7 @@ ctx.setFullReset(true);
|
|
|
582
653
|
|
|
583
654
|
### Step-Level Reset Options
|
|
584
655
|
|
|
585
|
-
A step can reset the conversation when the conversation enters it:
|
|
656
|
+
A step can reset the conversation when the conversation enters it. A step with any reset setting is terminal: the platform runs the reset in place of the step's text, and step mode ends there, so use it for a step that hands the call over to a new prompt. Rendering logs `step_reset_is_terminal` for it, and `context_reset_without_system_prompt` for a context's `setConsolidate()`, `setFullReset()` or `setUserPrompt()` without a system prompt, since a context's reset runs only with one:
|
|
586
657
|
|
|
587
658
|
```typescript
|
|
588
659
|
const step = ctx.addStep('fresh_start');
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
# Conversation Patterns
|
|
2
|
+
|
|
3
|
+
Each pattern here keeps a decision in your code that the model would otherwise make from the conversation. The helpers are exported from the package root, `@signalwire/sdk`.
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Confirming a Change](#confirming-a-change)
|
|
8
|
+
- [Read-Backs Callers Can Interrupt](#read-backs-callers-can-interrupt)
|
|
9
|
+
- [Recording What Was Done](#recording-what-was-done)
|
|
10
|
+
- [Questions That Carry Content](#questions-that-carry-content)
|
|
11
|
+
- [The Caller's Own Words](#the-callers-own-words)
|
|
12
|
+
- [Numbers the Way a Voice Should Say Them](#numbers-the-way-a-voice-should-say-them)
|
|
13
|
+
- [Tool Outcomes the Model Can Trust](#tool-outcomes-the-model-can-trust)
|
|
14
|
+
- [Requests to Come Back To](#requests-to-come-back-to)
|
|
15
|
+
- [What a Caller Spelled](#what-a-caller-spelled)
|
|
16
|
+
- [Testing a Call Flow](#testing-a-call-flow)
|
|
17
|
+
|
|
18
|
+
Several of these patterns use semantic gate keys, params and actions (`dialogue`, `history`, `since`, `unclear`, `on_unclear`, `semantic_gate_dialogue`, `unavailable_function_response`, `semantic_gate_mark` and `expected_answer`) that need a platform release that has them. A release with semantic gates but without one of the gate keys refuses the whole function. See [Semantic gates](api-reference.md#semantic-gates).
|
|
19
|
+
|
|
20
|
+
## Confirming a Change
|
|
21
|
+
|
|
22
|
+
A change the caller must agree to, such as placing an order or cancelling an account, needs a yes to that change, not a yes somewhere in the call. The platform's confirm pattern does this with semantic gates:
|
|
23
|
+
|
|
24
|
+
1. A function proposes the change. It reads the change back and records it in `semantic_state`, in one action object, so the proposal's dialogue starts with the read-back.
|
|
25
|
+
2. The tool that carries out the change has three gates, each judged on the proposal's dialogue: the caller's latest turn is an answer, the answer is a yes, and what they answered was a read-back of this change.
|
|
26
|
+
|
|
27
|
+
`Proposal` builds both halves. The gates' questions are the platform's own, which were replayed against logged confirmation checks.
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { AgentBase, Proposal, current } from '@signalwire/sdk';
|
|
31
|
+
|
|
32
|
+
const agent = new AgentBase({ name: 'orders', route: '/orders' });
|
|
33
|
+
const order = new Proposal('place_order', { declineTool: 'change_order' });
|
|
34
|
+
|
|
35
|
+
agent.defineTool({
|
|
36
|
+
name: 'review_order',
|
|
37
|
+
description: 'Read the order back to the caller',
|
|
38
|
+
parameters: { item: { type: 'string', description: 'The item, with its size' } },
|
|
39
|
+
required: ['item'],
|
|
40
|
+
handler: (args, rawData) =>
|
|
41
|
+
order.propose(`That's ${args.item} for pickup. Is that right?`, {
|
|
42
|
+
rawData,
|
|
43
|
+
details: { item: args.item },
|
|
44
|
+
}),
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
agent.defineTool({
|
|
48
|
+
name: 'place_order',
|
|
49
|
+
description: 'Place the order the caller said yes to',
|
|
50
|
+
handler: (_args, rawData) => {
|
|
51
|
+
const item = String(current(rawData)?.['item']);
|
|
52
|
+
return order.complete(`The order for ${item} is placed.`);
|
|
53
|
+
},
|
|
54
|
+
gates: order.confirmGates(),
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`propose()` says the read-back word for word, records `{ proposal: readBack, revision: n }` with your details, and has the model wait for the caller's answer. `current(rawData)` reads the proposal back from a request's `global_data.semantic_state`. When a gate blocks the confirm tool, the model is told why, with the proposal quoted from `semantic_state`, and chaining is turned off for the call (`backToBackFunctions(false)`), so it answers in words before it calls a tool again. To read the same change back again, use `askAgain(rawData)`: the platform marks a new proposal only when `semantic_state` changes, so it records the next revision.
|
|
59
|
+
|
|
60
|
+
`new Proposal(confirmTool, { unclear: true, threshold: 0.6 })` lets the gates answer unclear as well, where the gate provider can, which asks the caller again. Give the confirm step only the confirm tool, the decline tool and a tool that notes other requests, so a "yes, and also..." becomes two calls.
|
|
61
|
+
|
|
62
|
+
## Read-Backs Callers Can Interrupt
|
|
63
|
+
|
|
64
|
+
A caller often answers before a read-back ends. Order it so the part they must hear comes first:
|
|
65
|
+
|
|
66
|
+
1. The change itself: "That's a large tea, not a small one."
|
|
67
|
+
2. The details of the change: "for pickup at five, on the card ending in one two three four."
|
|
68
|
+
3. What was already settled, last: "at the Main Street store."
|
|
69
|
+
|
|
70
|
+
A caller who cuts it off has heard the change. The confirm gates count a yes once the caller has heard what the change is, so a read-back that leads with it confirms sooner.
|
|
71
|
+
|
|
72
|
+
## Recording What Was Done
|
|
73
|
+
|
|
74
|
+
After the change is carried out, write a `semantic_state` that records it, rather than clearing it with `{}`. `Proposal.complete(summary)` does this. A state that changes starts the next proposal's dialogue there, so a later confirmation isn't judged on what was said before this one, and the model and the gates see what's settled.
|
|
75
|
+
|
|
76
|
+
## Questions That Carry Content
|
|
77
|
+
|
|
78
|
+
A one-word answer is hard to judge: "yes" may answer something else the agent said. Ask questions whose answers carry content. "Which size would you like, small or large?" gets "large", which a gate, the recognizer and your code can check. "Do you want a large?" gets "yes".
|
|
79
|
+
|
|
80
|
+
## The Caller's Own Words
|
|
81
|
+
|
|
82
|
+
A tool can check that an argument is something the caller said, rather than something the model inferred.
|
|
83
|
+
|
|
84
|
+
`defineTool({ ..., vouched: true })` asks the model. The tool gets a required boolean, `data_supplied_by_user`, and runs only when the model sets it to `true`. Otherwise the model is told to get the answer from the caller first.
|
|
85
|
+
|
|
86
|
+
`callerTurns(rawData)` reads what the caller said from the request's conversation. A request carries the conversation only with `swaig_post_conversation` on, and `needsConversation: true` on the tool turns it on.
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { AgentBase, FunctionResult, callerTurns } from '@signalwire/sdk';
|
|
90
|
+
|
|
91
|
+
const agent = new AgentBase({ name: 'stores', route: '/stores' });
|
|
92
|
+
|
|
93
|
+
agent.defineTool({
|
|
94
|
+
name: 'find_store',
|
|
95
|
+
description: 'Find the store nearest a ZIP code',
|
|
96
|
+
parameters: { zip: { type: 'string', description: "The caller's ZIP code" } },
|
|
97
|
+
required: ['zip'],
|
|
98
|
+
needsConversation: true,
|
|
99
|
+
handler: (args, rawData) => {
|
|
100
|
+
const said = callerTurns(rawData, undefined, { last: 3 }).join(' ');
|
|
101
|
+
if (!said.replaceAll(' ', '').includes(args.zip)) {
|
|
102
|
+
return new FunctionResult().setToolResponse(
|
|
103
|
+
'find_store was not run.',
|
|
104
|
+
'Ask the caller for their ZIP code.',
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
return new FunctionResult().setToolResponse(
|
|
108
|
+
`The nearest store to ${args.zip} is on Main Street.`,
|
|
109
|
+
);
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The conversation has the recognizer's final text, after hearing hints and number formatting. For the words as the recognizer heard them, with a confidence for each, call `agent.recordSpeechFinals()` and read `agent.speechFinals(rawData.call_id)`. The finals come from the platform's `ai.speech_detect` events, which the agent receives at its own `/ai_events` endpoint. A handler can ask the caller again about a word the recognizer wasn't sure of, such as a letter of a spelled name. `agent.onAiEvent(handler)` receives every AI event the platform posts. Set both on the agent itself, not in a dynamic config callback: the `/ai_events` endpoint runs on the agent, not on a per-request copy. See [AI Event Methods](api-reference.md#ai-event-methods).
|
|
115
|
+
|
|
116
|
+
## Numbers the Way a Voice Should Say Them
|
|
117
|
+
|
|
118
|
+
The platform normalizes text before its pronunciation rules run, so a bare number is already words by then. A ZIP code given as "10001" can be read "ten thousand one", and `addPronunciation()` can't change that. Give the words to say instead:
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
import { sayDigits, sayLastDigits, sayMoney } from '@signalwire/sdk';
|
|
122
|
+
|
|
123
|
+
sayDigits('415-555-0192'); // "four one five, five five five, zero one nine two"
|
|
124
|
+
sayDigits('10001', undefined, { zero: 'oh' }); // "one oh oh oh one"
|
|
125
|
+
sayLastDigits('4111111111111234'); // "one two three four"
|
|
126
|
+
sayMoney(14.5); // "fourteen dollars and fifty cents"
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Use them in a `say` action, or in the tool result the model reads back. They're English. `sayDigits(text, group?)` takes a group size, or a list of sizes such as `[3, 3, 4]`, in place of the text's own groups. `sayMoney(amount, currency?)` takes a number, a `bigint` or a decimal string such as `'14.50'`, and rounds half up from the amount's decimal text, so `sayMoney(2.675)` is "two dollars and sixty-eight cents". It knows USD, CAD, AUD, NZD, EUR, GBP, MXN, INR and JPY. `numberWords(n)` takes a safe integer or a `bigint` below a quadrillion: `numberWords(1405)` is "one thousand four hundred five".
|
|
130
|
+
|
|
131
|
+
When a step asks for a number with a known length, `step.setExpectedAnswer(5)` tells the recognizer to end its wait once the caller has said that many digits. See the [Contexts and Steps Guide](contexts-guide.md#expected-answers).
|
|
132
|
+
|
|
133
|
+
## Tool Outcomes the Model Can Trust
|
|
134
|
+
|
|
135
|
+
The model reads a tool's result as what happened, so the result must not claim more than the handler knows.
|
|
136
|
+
|
|
137
|
+
- Throw `new ToolRefusal(toolResult, toolPrompt)` to decline a call with an outcome you know, such as an item out of stock.
|
|
138
|
+
- Any other error tells the model the function failed before it finished, so whether it took effect is unknown, and not to tell the caller it worked or that it didn't. The error is logged, not sent. A tool's `onError` hook or `errorMessage` still takes its place when you give one.
|
|
139
|
+
- An object without a `response` or an `action` is the handler's data, and the model gets it as JSON.
|
|
140
|
+
|
|
141
|
+
SignalWire sends a tool request again after a timeout, a failed connection or a 5xx, so a slow tool could run twice. The agent answers such a retry with the first attempt's result, and one that arrives while the first is still running waits for it. `agent.setToolResendDedupe(false)` turns this off. The record is kept in the agent's process: with several processes or replicas, a retry that reaches another one runs the tool again, so make tools that change things safe to run twice. The dedupe is the first [tool middleware](api-reference.md#addtoolmiddlewaremiddleware) around every call.
|
|
142
|
+
|
|
143
|
+
## Requests to Come Back To
|
|
144
|
+
|
|
145
|
+
A caller in the middle of one task often asks for another: "and can you also check my balance?" Taking it up at once loses the first task, and ignoring it loses the second. `RequestList` keeps such requests in the call's `global_data`. A tool notes each one, and the model tells the caller it's noted for right after this. The step text shows the list, so the agent takes the requests up when the current task is done.
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { AgentBase, RequestList } from '@signalwire/sdk';
|
|
149
|
+
|
|
150
|
+
const agent = new AgentBase({ name: 'support', route: '/support' });
|
|
151
|
+
const later = new RequestList('later', {
|
|
152
|
+
openers: { balance: 'You also asked about your balance.' },
|
|
153
|
+
});
|
|
154
|
+
agent.setGlobalData(later.defaults());
|
|
155
|
+
|
|
156
|
+
agent.defineTool({
|
|
157
|
+
name: 'note_request',
|
|
158
|
+
description: 'Note something the caller asked to do later',
|
|
159
|
+
parameters: {
|
|
160
|
+
kind: { type: 'string', enum: ['balance', 'question'] },
|
|
161
|
+
about: { type: 'string', description: 'What the caller asked, in a few words' },
|
|
162
|
+
},
|
|
163
|
+
required: ['kind', 'about'],
|
|
164
|
+
handler: (args, rawData) => later.note(rawData, args.kind, args.about),
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
const ctx = agent.defineContexts().addContext('default');
|
|
168
|
+
ctx.addStep('take_order').setText('Take the order.\n\n${global_data.later_text}');
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
`later.next(rawData)` gives the oldest request with its opener, and `later.done(rawData)` removes it once it's taken up. The kinds and their openers are yours; an opener's `{about}` is replaced by what the request is about. Current platform releases expand the step's text again when the list changes, so it shows at the next request. Earlier releases, and a realtime model, keep the list from the step's entry: return `refreshStep()` with the note there to show it at once.
|
|
172
|
+
|
|
173
|
+
## What a Caller Spelled
|
|
174
|
+
|
|
175
|
+
A caller spells a name, a code or an email address in many ways: letter by letter, with letter names, with "S as in Sam", with the NATO alphabet, or with "double l". `readSpelled`, `spokenEmail` and `spellingVariants` read them all from the recognizer's text.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { readSpelled, spellingVariants, spokenEmail } from '@signalwire/sdk';
|
|
179
|
+
|
|
180
|
+
readSpelled('S as in Sam, m i t h'); // ['S', 'M', 'I', 'T', 'H']
|
|
181
|
+
readSpelled('sierra mike india tango hotel'); // ['S', 'M', 'I', 'T', 'H']
|
|
182
|
+
readSpelled('one two oh four', { ohIsZero: true }); // ['1', '2', '0', '4']
|
|
183
|
+
spokenEmail('john dot smith at example dot com'); // 'john.smith@example.com'
|
|
184
|
+
spellingVariants(['S', 'M', 'I', 'T', 'H'], { S: 'F', M: 'N' });
|
|
185
|
+
// ['SMITH', 'FMITH', 'SNITH', 'FNITH']
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The recognizer confuses some letters, and which ones depends on the recognizer and the voice, so `spellingVariants` takes confusion groups you measure on your own calls; none are built in. A group is a string of units or a list of them, and the groups may be a plain object or a `Map`. Its `positions` option limits the changes to the letters the recognizer was least sure of, which `agent.speechFinals()` gives a confidence for, and `limit` (default 50) caps the spellings. Look each variant up in your records, in order: the first that matches is the likeliest.
|
|
189
|
+
|
|
190
|
+
## Testing a Call Flow
|
|
191
|
+
|
|
192
|
+
`swaig-test` runs one tool call. To test a flow, such as a confirmation across steps, `CallSimulator` runs the agent's tools through a simulated call. It reads the agent's rendered SWML as the platform would, and checks each call as the platform does: a tool the current step doesn't offer doesn't run, and a gated tool runs only when your gate callback lets it. Each result's actions change the call: global data and `semantic_state`, the step and context, the functions turned on, `say`, and the end of the call. A tool runs as the agent's `/swaig` route runs it: through the `onFunctionCall` hook, then the tool with its middleware and the outcome rules above.
|
|
193
|
+
|
|
194
|
+
`call()` and `replay()` are async, so await them. This runs as a script; in a test, the same calls go inside the test function.
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import assert from 'node:assert/strict';
|
|
198
|
+
import { AgentBase, CallSimulator, Proposal } from '@signalwire/sdk';
|
|
199
|
+
|
|
200
|
+
const agent = new AgentBase({ name: 'orders', route: '/orders' });
|
|
201
|
+
const order = new Proposal('place_order');
|
|
202
|
+
|
|
203
|
+
agent.defineTool({
|
|
204
|
+
name: 'review_order',
|
|
205
|
+
description: 'Read the order back to the caller',
|
|
206
|
+
parameters: { item: { type: 'string', description: 'The item' } },
|
|
207
|
+
required: ['item'],
|
|
208
|
+
handler: (args, rawData) =>
|
|
209
|
+
order
|
|
210
|
+
.propose(`That's ${args.item}. Is that right?`, { rawData, details: { item: args.item } })
|
|
211
|
+
.swmlChangeStep('confirm'),
|
|
212
|
+
});
|
|
213
|
+
agent.defineTool({
|
|
214
|
+
name: 'place_order',
|
|
215
|
+
description: 'Place the order the caller said yes to',
|
|
216
|
+
handler: () => order.complete('The order is placed.'),
|
|
217
|
+
gates: order.confirmGates(),
|
|
218
|
+
});
|
|
219
|
+
const ctx = agent.defineContexts().addContext('default');
|
|
220
|
+
ctx.addStep('take_order').setText('Take the order.').setFunctions(['review_order']);
|
|
221
|
+
ctx.addStep('confirm').setText('Confirm it.').setFunctions(['place_order']);
|
|
222
|
+
|
|
223
|
+
const sim = new CallSimulator(agent, { gates: () => true });
|
|
224
|
+
sim.caller('A large tea, please.');
|
|
225
|
+
assert.equal((await sim.call('place_order')).ran, false); // not offered until the read-back
|
|
226
|
+
await sim.call('review_order', { item: 'a large tea' });
|
|
227
|
+
sim.caller('Yes.');
|
|
228
|
+
assert.equal((await sim.call('place_order')).ran, true);
|
|
229
|
+
assert.deepEqual(sim.semanticState, { done: 'The order is placed.' });
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
The gate callback gets each gate, the simulator and the call's arguments, and returns `true`, `false`, a probability compared with the gate's threshold, or `'unclear'`, or a promise of one. A blocked call's `blockedBy` is `'step'` or the id of the gate that blocked it. `sim.gateConversation(gate)` gives the dialogue that gate would judge: the spoken turns the model sees, chosen by its window, proposal or mark. `sim.modelView()` gives what the model gets now, after each step's history mode, and a `post_process` result's actions run after `sim.agentSays()`. With `checkToolMentions: true`, a call whose result names a tool that the step it leaves the call in doesn't offer rejects with a `ToolMentionError`: the model would read the name and might call a tool it doesn't have. Give `stubs` for DataMap tools, which run on the platform. `sim.marks` is a `Map` from each gate mark's name to its place in `sim.callLog`.
|
|
233
|
+
|
|
234
|
+
The simulator renders and runs tools on the agent itself: it doesn't make the per-request copy a dynamic config callback configures. It doesn't run a model, gather questions, or the gates' decision model.
|
|
235
|
+
|
|
236
|
+
To check changed code against real calls, record tool requests with `RequestRecorder`, which is tool middleware, and run them again with `replay()`:
|
|
237
|
+
|
|
238
|
+
<!-- snippet: no-run writes a recording file next to the snippet; illustrative -->
|
|
239
|
+
```ts
|
|
240
|
+
import { AgentBase, CallSimulator, RequestRecorder } from '@signalwire/sdk';
|
|
241
|
+
|
|
242
|
+
const agent = new AgentBase({ name: 'orders', route: '/orders' });
|
|
243
|
+
const recorder = new RequestRecorder('tool_requests.jsonl');
|
|
244
|
+
agent.addToolMiddleware(recorder.middleware);
|
|
245
|
+
|
|
246
|
+
// Later, against changed code:
|
|
247
|
+
const outcomes = await new CallSimulator(agent).replay(RequestRecorder.load('tool_requests.jsonl'));
|
|
248
|
+
console.log(outcomes.map((o) => o.response));
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
The recorder appends each request to the file, one JSON object a line, in the order they came, and keeps the newest `limit` (default 1000) in `recorder.requests`. The requests carry what callers said, so keep a recording where you'd keep call recordings.
|
|
252
|
+
|
|
253
|
+
## Related Documentation
|
|
254
|
+
|
|
255
|
+
- [API Reference](api-reference.md#semantic-gates): semantic gates and every tool option
|
|
256
|
+
- [SWAIG Reference](swaig-reference.md): every `FunctionResult` action
|
|
257
|
+
- [Contexts and Steps Guide](contexts-guide.md): steps, their function lists and expected answers
|
package/docs/mcp_integration.md
CHANGED
|
@@ -96,7 +96,7 @@ The endpoint takes JSON-RPC 2.0 requests as POSTs. It answers `404` to a GET, si
|
|
|
96
96
|
|
|
97
97
|
The endpoint lists and calls only the tools the agent runs itself. DataMap tools run on SignalWire, and external webhook tools (a `webhookUrl` on the tool) run on another server. `/mcp` doesn't list them, and `tools/call` answers `Unknown tool` for them.
|
|
98
98
|
|
|
99
|
-
A `tools/call` result carries the tool's `response` text as MCP text content. A structured `{ tool_result, tool_prompt }` response is sent as its JSON. Actions in the result, such as a transfer, have no meaning outside a call and aren't sent. A handler that throws gets the same result a SWAIG call gets: its `onError` hook's result, its `errorMessage`, or
|
|
99
|
+
A `tools/call` result carries the tool's `response` text as MCP text content. A structured `{ tool_result, tool_prompt }` response is sent as its JSON. Actions in the result, such as a transfer, have no meaning outside a call and aren't sent. A handler that throws gets the same result a SWAIG call gets: its `onError` hook's result, its `errorMessage`, or the result that tells the model the outcome is unknown, with `isError: false`. The exception's message doesn't reach the client.
|
|
100
100
|
|
|
101
101
|
Requests to `/mcp` run on the agent itself, not on a per-request copy. A dynamic config callback or `addPerCallConfig()` doesn't run for them, so tools those callbacks register aren't available. The handler's `rawData` holds only `function` and `argument`, with no `call_id` or `global_data`.
|
|
102
102
|
|
package/docs/pgi_agent_guide.md
CHANGED
|
@@ -317,6 +317,11 @@ List allowed model transitions when the model can choose among safe destinations
|
|
|
317
317
|
- `default`: remove prior step instructions and keep the dialogue; the behavior when unset.
|
|
318
318
|
- `hide`: remove prior instructions and dialogue from the model's view. Use `${step_history.*}` references in the step's text to bring back selected information.
|
|
319
319
|
- `isolate`: like `hide`, but only while the agent is in this step. When the step is left, the earlier dialogue returns and the step's own turns stay; the earlier instructions stay cleared, and what an earlier `hide` step hid stays hidden. Entering the step again isolates it again. Use it for a step that must see nothing else, such as a confirmation read-back. A platform without `isolate` treats it as `default`.
|
|
320
|
+
- `spoken`: remove prior instructions and every earlier tool call, tool result and turn-scoped system note (tool prompts, `ai-msg` injections, a gather's preamble) for the rest of the call, while keeping every spoken turn, the caller's and the agent's. A platform without `spoken` treats it as `default`.
|
|
321
|
+
|
|
322
|
+
`hide`, `isolate` and `spoken` keep the exchange that entered the step, as its start: the call whose action changed the step, with its result, notes and `say`, so a confirm step entered from a tool keeps the read-back the caller just heard. A `post_process` action's change, which runs after the model's reply, keeps the call and everything stored from it on, the reply included. A change by `next_step` keeps nothing, and platform releases before this keep nothing under `hide` and `isolate`.
|
|
323
|
+
|
|
324
|
+
Between the stages of a task, choose by what must survive. Use `spoken` at a stage boundary where the caller's earlier requests must stay but the finished stage's lookups shouldn't: a model that sees old tool results tends to call tools the current step doesn't offer. Use `isolate` on a confirm step. Use `hide` only where earlier talk must never come back, because it takes the caller's earlier requests too, from the model and from the semantic gates. Put any result the next stage needs in `global_data`, and show it in the step's text.
|
|
320
325
|
|
|
321
326
|
Hidden turns remain in the call log, so don't describe `hide` as deletion. `Context.setIsolated()`, `setSystemPrompt()`, `setUserPrompt()`, `setConsolidate()` and `setFullReset()` add more controls for entering a context. Steps have `setResetSystemPrompt()`, `setResetUserPrompt()`, `setResetConsolidate()` and `setResetFullReset()`. Verify the combination you choose on the runtime rather than treating them all as a memory wipe. [S03]
|
|
322
327
|
|
|
@@ -103,7 +103,7 @@ This is the difference between telling someone not to open a door and removing t
|
|
|
103
103
|
|
|
104
104
|
### Layer 3: Transition scope
|
|
105
105
|
|
|
106
|
-
Each step in a conversation declares which steps the model may move to next. The enforcement is mechanical and lives in the schema, not in the model's judgment.
|
|
106
|
+
Each step in a conversation declares which steps the model may move to next. The enforcement is mechanical and lives in the schema, not in the model's judgment. Each time a step loads, the platform rewrites the argument schema of the model's transition tool, `next_step`, so that only whitelisted step names exist as options. The model cannot request a transition to a step that is not on the list. The reason is the same as for a tool that is not in its schema: the option is not part of its world. An empty whitelist leaves the model no step it can request.
|
|
107
107
|
|
|
108
108
|
The whitelist constrains the model, not the software. Tool handlers, which are the developer's deterministic code, retain full transition authority. They can move the conversation to any step in the current context, or to another context, as the business logic requires. This is the authority inversion applied to control flow. The model can only request movements the system pre-approved, while the software that owns the state machine moves the conversation wherever the rules say. In the blackjack example, `playing` whitelists only `hand_complete`, so the model can't talk its way anywhere else. The `hit` handler, on detecting a bust, moves the conversation straight to `you_lost` with `swmlChangeStep()`. The software is the authority, and the whitelist was never a constraint on it.
|
|
109
109
|
|
|
@@ -243,7 +243,7 @@ PGI restores programming to the equation. In PGI, the developer's traditional sk
|
|
|
243
243
|
|
|
244
244
|
A developer building an intake system writes a gather sequence. The platform presents the model with one question at a time and a single submission tool, `gather_submit`. The tool's schema is rebuilt for each question, with that answer's type and, when the question asks for it, a required confirmation. The model does not know how many questions remain or what the full form looks like. When an answer arrives, the platform stores it in `global_data` and silently advances to the next question. When the sequence is complete, the accumulated structured data is handed off to the next phase of the workflow. There, a handler validates the whole record before anything consequential uses it. The model never saw the form. It never had the opportunity to skip ahead, reorder questions, or submit answers to questions that were never asked.
|
|
245
245
|
|
|
246
|
-
Visibility of what came before is itself a dial the developer controls. By default, each new phase withdraws the prior phase's instructions from the model's context while the conversation itself remains visible. At stricter settings, the platform pulls the earlier dialogue out entirely, or hides the answers already collected so the model must ask rather than infer. A hidden phase can also be brought back on purpose. The platform can hand the model a summary of an earlier phase instead of the raw transcript. The summary is one more curated projection in place of the full truth. Reality authoring extends to the past, not only the present. In the SDK, these settings are `setHistory()` on a step or context (`keep`, `default`, `hide`,
|
|
246
|
+
Visibility of what came before is itself a dial the developer controls. By default, each new phase withdraws the prior phase's instructions from the model's context while the conversation itself remains visible. At stricter settings, the platform pulls the earlier dialogue out entirely, or hides the answers already collected so the model must ask rather than infer. A hidden phase can also be brought back on purpose. The platform can hand the model a summary of an earlier phase instead of the raw transcript. The summary is one more curated projection in place of the full truth. Reality authoring extends to the past, not only the present. In the SDK, these settings are `setHistory()` on a step or context (`keep`, `default`, `hide`, `isolate`, which hides the earlier dialogue only while the agent is in that step, or `spoken`, which drops the earlier tool exchanges and keeps what was said) and the `isolated` option of `setGatherInfo()` and `addGatherQuestion()`. A `${step_history.*}` reference in a step's text chooses what comes back. The call log keeps every message either way.
|
|
247
247
|
|
|
248
248
|
This is not the same as ordinary backend validation (clamping a quantity with `if (quantity > 20) quantity = 20;`, or rejecting a bad input). Those are single lines of defensive code any backend performs. The gather sequence is reality authoring. The developer constructs what the model believes to be true at each moment, and `global_data` carries the accumulated truth the model never sees.
|
|
249
249
|
|