@signalwire/sdk 2.0.0
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/.github/workflows/publish.yml +27 -0
- package/.github/workflows/test.yml +17 -0
- package/CLAUDE.md +112 -0
- package/README.md +254 -0
- package/docs/MIGRATION-2.0.md +81 -0
- package/docs/agent-guide.md +869 -0
- package/docs/agent_guide.md +1026 -0
- package/docs/api-reference.md +2420 -0
- package/docs/api_reference.md +1301 -0
- package/docs/architecture.md +843 -0
- package/docs/cli-guide.md +579 -0
- package/docs/cli_guide.md +448 -0
- package/docs/cloud_functions_guide.md +474 -0
- package/docs/configuration.md +422 -0
- package/docs/contexts-guide.md +787 -0
- package/docs/contexts_guide.md +511 -0
- package/docs/datamap-guide.md +1141 -0
- package/docs/datamap_guide.md +595 -0
- package/docs/llm_parameters.md +239 -0
- package/docs/mcp_gateway_reference.md +648 -0
- package/docs/mcp_integration.md +108 -0
- package/docs/prefabs-guide.md +800 -0
- package/docs/sdk_features.md +477 -0
- package/docs/security.md +436 -0
- package/docs/serverless-guide.md +513 -0
- package/docs/skills-guide.md +857 -0
- package/docs/skills-system.md +301 -0
- package/docs/skills_parameter_schema.md +392 -0
- package/docs/skills_system.md +467 -0
- package/docs/swaig-reference.md +1627 -0
- package/docs/swaig_reference.md +910 -0
- package/docs/swml_service_guide.md +600 -0
- package/docs/third_party_skills.md +533 -0
- package/docs/web_service.md +677 -0
- package/examples/README.md +131 -0
- package/examples/advanced-datamap.ts +100 -0
- package/examples/advanced-dynamic-config.ts +70 -0
- package/examples/auto-vivified.ts +94 -0
- package/examples/call-flow.ts +63 -0
- package/examples/comprehensive-dynamic.ts +125 -0
- package/examples/contexts-steps.ts +65 -0
- package/examples/custom-path.ts +45 -0
- package/examples/datamap-tools.ts +55 -0
- package/examples/datasphere-multi-instance.ts +63 -0
- package/examples/datasphere-serverless-env.ts +68 -0
- package/examples/datasphere-webhook-env.ts +66 -0
- package/examples/datasphere.ts +37 -0
- package/examples/declarative.ts +100 -0
- package/examples/dynamic-config.ts +54 -0
- package/examples/dynamic-info-gatherer.ts +69 -0
- package/examples/dynamic-swml-service.ts +67 -0
- package/examples/gather-info.ts +71 -0
- package/examples/gather-per-question-functions-demo.ts +140 -0
- package/examples/joke-agent.ts +34 -0
- package/examples/kubernetes-agent.ts +45 -0
- package/examples/llm-params.ts +69 -0
- package/examples/mcp-agent.ts +84 -0
- package/examples/mcp-gateway.ts +35 -0
- package/examples/multi-agent.ts +73 -0
- package/examples/multi-endpoint.ts +79 -0
- package/examples/pom-prompt.ts +71 -0
- package/examples/prefab-concierge.ts +47 -0
- package/examples/prefab-faq.ts +54 -0
- package/examples/prefab-info-gatherer.ts +33 -0
- package/examples/prefab-receptionist.ts +36 -0
- package/examples/prefab-survey.ts +68 -0
- package/examples/record-call.ts +67 -0
- package/examples/relay-demo.ts +33 -0
- package/examples/room-and-sip.ts +94 -0
- package/examples/serverless-lambda.ts +35 -0
- package/examples/session-state.ts +83 -0
- package/examples/simple-agent.ts +36 -0
- package/examples/simple-static.ts +29 -0
- package/examples/skills-demo.ts +38 -0
- package/examples/step-function-inheritance-demo.ts +124 -0
- package/examples/swaig-features.ts +187 -0
- package/examples/swml-service-routing.ts +66 -0
- package/examples/swml-service.ts +38 -0
- package/examples/tap.ts +68 -0
- package/examples/verb-methods.ts +45 -0
- package/examples/web-search-multi-instance.ts +72 -0
- package/examples/web-search.ts +38 -0
- package/examples/wikipedia.ts +36 -0
- package/livewire/README.md +140 -0
- package/livewire/docs/migration-guide.md +228 -0
- package/livewire/examples/livewire-basic-agent.ts +74 -0
- package/livewire/examples/livewire-handoff.ts +197 -0
- package/livewire/examples/livewire-multi-tool.ts +117 -0
- package/package.json +38 -0
- package/relay/README.md +70 -0
- package/relay/RELAY_IMPLEMENTATION_GUIDE.md +1257 -0
- package/relay/docs/call-methods.md +474 -0
- package/relay/docs/client-reference.md +142 -0
- package/relay/docs/events.md +134 -0
- package/relay/docs/getting-started.md +134 -0
- package/relay/docs/guide.md +306 -0
- package/relay/docs/messaging.md +182 -0
- package/relay/examples/relay-inbound.ts +66 -0
- package/relay/examples/relay-messaging.ts +71 -0
- package/relay/examples/relay-outbound.ts +76 -0
- package/rest/README.md +95 -0
- package/rest/docs/calling.md +273 -0
- package/rest/docs/client-reference.md +107 -0
- package/rest/docs/compat.md +204 -0
- package/rest/docs/fabric.md +183 -0
- package/rest/docs/getting-started.md +110 -0
- package/rest/docs/guide.md +351 -0
- package/rest/docs/namespaces.md +285 -0
- package/rest/examples/rest-10dlc-registration.ts +161 -0
- package/rest/examples/rest-calling-ivr-and-ai.ts +102 -0
- package/rest/examples/rest-calling-play-and-record.ts +91 -0
- package/rest/examples/rest-client.ts +65 -0
- package/rest/examples/rest-compat-laml.ts +210 -0
- package/rest/examples/rest-datasphere-search.ts +82 -0
- package/rest/examples/rest-fabric-conferences-and-routing.ts +144 -0
- package/rest/examples/rest-fabric-subscribers-and-sip.ts +108 -0
- package/rest/examples/rest-fabric-swml-and-callflows.ts +99 -0
- package/rest/examples/rest-manage-resources.ts +65 -0
- package/rest/examples/rest-phone-number-management.ts +197 -0
- package/rest/examples/rest-queues-mfa-and-recordings.ts +143 -0
- package/rest/examples/rest-video-rooms.ts +186 -0
- package/src/AgentBase.ts +2489 -0
- package/src/AgentServer.ts +415 -0
- package/src/AuthHandler.ts +256 -0
- package/src/ConfigLoader.ts +447 -0
- package/src/ContextBuilder.ts +1150 -0
- package/src/DataMap.ts +449 -0
- package/src/FunctionResult.ts +866 -0
- package/src/Logger.ts +337 -0
- package/src/PomBuilder.ts +439 -0
- package/src/PromptManager.ts +133 -0
- package/src/SWMLHandler.ts +298 -0
- package/src/SWMLService.ts +717 -0
- package/src/SchemaUtils.ts +361 -0
- package/src/SecurityUtils.ts +153 -0
- package/src/ServerlessAdapter.ts +221 -0
- package/src/SessionManager.ts +311 -0
- package/src/SslConfig.ts +118 -0
- package/src/SwaigFunction.ts +276 -0
- package/src/SwmlBuilder.ts +258 -0
- package/src/SwmlVerbMethods.generated.ts +234 -0
- package/src/TypeInference.ts +181 -0
- package/src/WebService.ts +619 -0
- package/src/cli/agent-loader.ts +166 -0
- package/src/cli/mock-data.ts +111 -0
- package/src/cli/swaig-test.ts +452 -0
- package/src/generateVerbTypes.ts +322 -0
- package/src/index.ts +167 -0
- package/src/livewire/index.ts +950 -0
- package/src/prefabs/ConciergeAgent.ts +287 -0
- package/src/prefabs/FAQBotAgent.ts +384 -0
- package/src/prefabs/InfoGathererAgent.ts +339 -0
- package/src/prefabs/ReceptionistAgent.ts +366 -0
- package/src/prefabs/SurveyAgent.ts +646 -0
- package/src/prefabs/index.ts +27 -0
- package/src/relay/Action.ts +314 -0
- package/src/relay/Call.ts +854 -0
- package/src/relay/Deferred.ts +71 -0
- package/src/relay/Message.ts +148 -0
- package/src/relay/RelayClient.ts +1036 -0
- package/src/relay/RelayError.ts +14 -0
- package/src/relay/RelayEvent.ts +892 -0
- package/src/relay/constants.ts +132 -0
- package/src/relay/index.ts +123 -0
- package/src/relay/types.ts +149 -0
- package/src/rest/HttpClient.ts +103 -0
- package/src/rest/RestError.ts +31 -0
- package/src/rest/base/BaseResource.ts +19 -0
- package/src/rest/base/CrudResource.ts +51 -0
- package/src/rest/base/CrudWithAddresses.ts +26 -0
- package/src/rest/index.ts +200 -0
- package/src/rest/namespaces/addresses.ts +32 -0
- package/src/rest/namespaces/calling.ts +187 -0
- package/src/rest/namespaces/chat.ts +20 -0
- package/src/rest/namespaces/compat.ts +352 -0
- package/src/rest/namespaces/datasphere.ts +45 -0
- package/src/rest/namespaces/fabric.ts +222 -0
- package/src/rest/namespaces/imported-numbers.ts +20 -0
- package/src/rest/namespaces/logs.ts +84 -0
- package/src/rest/namespaces/lookup.ts +21 -0
- package/src/rest/namespaces/mfa.ts +30 -0
- package/src/rest/namespaces/number-groups.ts +38 -0
- package/src/rest/namespaces/phone-numbers.ts +44 -0
- package/src/rest/namespaces/project.ts +36 -0
- package/src/rest/namespaces/pubsub.ts +20 -0
- package/src/rest/namespaces/queues.ts +33 -0
- package/src/rest/namespaces/recordings.ts +28 -0
- package/src/rest/namespaces/registry.ts +101 -0
- package/src/rest/namespaces/short-codes.ts +28 -0
- package/src/rest/namespaces/sip-profile.ts +25 -0
- package/src/rest/namespaces/verified-callers.ts +27 -0
- package/src/rest/namespaces/video.ts +165 -0
- package/src/rest/pagination.ts +84 -0
- package/src/rest/types.ts +61 -0
- package/src/schema.json +12250 -0
- package/src/skills/SkillBase.ts +547 -0
- package/src/skills/SkillManager.ts +415 -0
- package/src/skills/SkillRegistry.ts +367 -0
- package/src/skills/builtin/api_ninjas_trivia.ts +280 -0
- package/src/skills/builtin/ask_claude.ts +241 -0
- package/src/skills/builtin/claude_skills.ts +978 -0
- package/src/skills/builtin/custom_skills.ts +312 -0
- package/src/skills/builtin/datasphere.ts +438 -0
- package/src/skills/builtin/datasphere_serverless.ts +339 -0
- package/src/skills/builtin/datetime.ts +130 -0
- package/src/skills/builtin/google_maps.ts +651 -0
- package/src/skills/builtin/index.ts +88 -0
- package/src/skills/builtin/info_gatherer.ts +405 -0
- package/src/skills/builtin/joke.ts +191 -0
- package/src/skills/builtin/math.ts +142 -0
- package/src/skills/builtin/mcp_gateway.ts +677 -0
- package/src/skills/builtin/native_vector_search.ts +901 -0
- package/src/skills/builtin/play_background_file.ts +358 -0
- package/src/skills/builtin/spider.ts +869 -0
- package/src/skills/builtin/swml_transfer.ts +635 -0
- package/src/skills/builtin/weather_api.ts +248 -0
- package/src/skills/builtin/web_search.ts +1074 -0
- package/src/skills/builtin/wikipedia_search.ts +299 -0
- package/src/skills/index.ts +12 -0
- package/src/types.ts +132 -0
- package/tests/AgentBase.test.ts +1093 -0
- package/tests/AgentServer.test.ts +126 -0
- package/tests/AuthHandler.test.ts +133 -0
- package/tests/ConfigLoader.test.ts +151 -0
- package/tests/ContextBuilder.test.ts +108 -0
- package/tests/DataMap.test.ts +367 -0
- package/tests/EphemeralSkillCopy.test.ts +107 -0
- package/tests/FunctionResult.test.ts +298 -0
- package/tests/GracefulShutdown.test.ts +46 -0
- package/tests/Logger.test.ts +420 -0
- package/tests/PomBuilder.test.ts +228 -0
- package/tests/ProxyDetection.test.ts +228 -0
- package/tests/SWMLService.test.ts +320 -0
- package/tests/SWMLVerbHandler.test.ts +523 -0
- package/tests/SchemaUtils.test.ts +106 -0
- package/tests/SchemaUtils.verb.test.ts +206 -0
- package/tests/SecurityUtils.test.ts +192 -0
- package/tests/ServerlessAdapter.test.ts +222 -0
- package/tests/SessionManager.test.ts +257 -0
- package/tests/SkillBaseFeatures.test.ts +130 -0
- package/tests/SkillMultiInstance.test.ts +102 -0
- package/tests/SkillParameterSchemas.test.ts +134 -0
- package/tests/SkillRegistrySchema.test.ts +84 -0
- package/tests/SslConfig.test.ts +97 -0
- package/tests/SwmlBuilder.test.ts +400 -0
- package/tests/TypeInference.test.ts +165 -0
- package/tests/VerbHandlerRegistry.test.ts +128 -0
- package/tests/cli/mock-data.test.ts +113 -0
- package/tests/cli/swaig-test.test.ts +108 -0
- package/tests/examples.test.ts +194 -0
- package/tests/fixtures/scrape-parity/README.md +53 -0
- package/tests/fixtures/scrape-parity/expected/01_simple_article.json +5 -0
- package/tests/fixtures/scrape-parity/expected/02_class_based_noise.json +5 -0
- package/tests/fixtures/scrape-parity/expected/03_nested_containers.json +5 -0
- package/tests/fixtures/scrape-parity/expected/04_bare_body.json +5 -0
- package/tests/fixtures/scrape-parity/expected/05_malformed.json +5 -0
- package/tests/fixtures/scrape-parity/expected/06_multi_class.json +5 -0
- package/tests/fixtures/scrape-parity/expected/07_anchor_pattern.json +5 -0
- package/tests/fixtures/scrape-parity/expected/08_inline_script.json +5 -0
- package/tests/fixtures/scrape-parity/expected/09_whitespace_nbsp.json +5 -0
- package/tests/fixtures/scrape-parity/expected/10_entity_unicode.json +5 -0
- package/tests/fixtures/scrape-parity/expected/11_cdata_comments.json +5 -0
- package/tests/fixtures/scrape-parity/expected/12_deep_nested_removals.json +5 -0
- package/tests/fixtures/scrape-parity/html/01_simple_article.html +18 -0
- package/tests/fixtures/scrape-parity/html/02_class_based_noise.html +18 -0
- package/tests/fixtures/scrape-parity/html/03_nested_containers.html +13 -0
- package/tests/fixtures/scrape-parity/html/04_bare_body.html +9 -0
- package/tests/fixtures/scrape-parity/html/05_malformed.html +11 -0
- package/tests/fixtures/scrape-parity/html/06_multi_class.html +18 -0
- package/tests/fixtures/scrape-parity/html/07_anchor_pattern.html +12 -0
- package/tests/fixtures/scrape-parity/html/08_inline_script.html +17 -0
- package/tests/fixtures/scrape-parity/html/09_whitespace_nbsp.html +21 -0
- package/tests/fixtures/scrape-parity/html/10_entity_unicode.html +10 -0
- package/tests/fixtures/scrape-parity/html/11_cdata_comments.html +13 -0
- package/tests/fixtures/scrape-parity/html/12_deep_nested_removals.html +24 -0
- package/tests/fixtures/scrape-parity/python_extract.py +109 -0
- package/tests/livewire/livewire.test.ts +780 -0
- package/tests/mcp.test.ts +221 -0
- package/tests/prefabs/prefabs.test.ts +1093 -0
- package/tests/relay/Action.test.ts +392 -0
- package/tests/relay/Call.test.ts +535 -0
- package/tests/relay/Deferred.test.ts +71 -0
- package/tests/relay/Message.test.ts +164 -0
- package/tests/relay/RelayClient.test.ts +779 -0
- package/tests/relay/RelayEvent.test.ts +463 -0
- package/tests/relay/helpers.ts +79 -0
- package/tests/rest/HttpClient.test.ts +274 -0
- package/tests/rest/RestError.test.ts +53 -0
- package/tests/rest/calling.test.ts +156 -0
- package/tests/rest/client.test.ts +197 -0
- package/tests/rest/compat.test.ts +335 -0
- package/tests/rest/datasphere.test.ts +71 -0
- package/tests/rest/fabric.test.ts +186 -0
- package/tests/rest/helpers.ts +95 -0
- package/tests/rest/logs.test.ts +68 -0
- package/tests/rest/pagination.test.ts +133 -0
- package/tests/rest/registry.test.ts +94 -0
- package/tests/rest/relay-rest.test.ts +290 -0
- package/tests/rest/video.test.ts +173 -0
- package/tests/setup.ts +6 -0
- package/tests/skills/SkillBase.test.ts +108 -0
- package/tests/skills/SkillManager.test.ts +268 -0
- package/tests/skills/SkillRegistry.test.ts +176 -0
- package/tests/skills/builtin.test.ts +1472 -0
- package/tests/skills/claude-skills.test.ts +54 -0
- package/tests/skills/custom-skills.test.ts +53 -0
- package/tests/skills/datasphere-serverless.test.ts +70 -0
- package/tests/skills/datasphere.test.ts +107 -0
- package/tests/skills/datetime.test.ts +101 -0
- package/tests/skills/google-maps.test.ts +78 -0
- package/tests/skills/info-gatherer.test.ts +411 -0
- package/tests/skills/joke.test.ts +81 -0
- package/tests/skills/math.test.ts +68 -0
- package/tests/skills/mcp-gateway.test.ts +101 -0
- package/tests/skills/play-background.test.ts +54 -0
- package/tests/skills/spider.test.ts +108 -0
- package/tests/skills/swml-transfer.test.ts +178 -0
- package/tests/skills/trivia.test.ts +54 -0
- package/tests/skills/vector-search.test.ts +135 -0
- package/tests/skills/weather-api.test.ts +77 -0
- package/tests/skills/web-search-parity.test.ts +59 -0
- package/tests/skills/web-search.test.ts +103 -0
- package/tests/skills/wikipedia.test.ts +63 -0
- package/tsconfig.json +18 -0
- package/vitest.config.ts +9 -0
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ConciergeAgent - Prefab agent that acts as a virtual concierge for a venue
|
|
3
|
+
* or business, providing information about services, amenities, and hours,
|
|
4
|
+
* and answering availability and directions questions.
|
|
5
|
+
*
|
|
6
|
+
* Ported from the Python SDK `signalwire.prefabs.concierge.ConciergeAgent`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { AgentBase } from '../AgentBase.js';
|
|
10
|
+
import { FunctionResult } from '../FunctionResult.js';
|
|
11
|
+
import type { AgentOptions } from '../types.js';
|
|
12
|
+
|
|
13
|
+
// ── Config types ────────────────────────────────────────────────────────────
|
|
14
|
+
|
|
15
|
+
export interface ConciergeConfig {
|
|
16
|
+
/** Name of the venue or business (required). */
|
|
17
|
+
venueName: string;
|
|
18
|
+
/** List of services offered by the venue (required). */
|
|
19
|
+
services: string[];
|
|
20
|
+
/** Dictionary of amenities, each mapping to a dict of detail keys/values. */
|
|
21
|
+
amenities: Record<string, Record<string, string>>;
|
|
22
|
+
/** Optional hours of operation by category (e.g. `{ default: "9 AM - 5 PM" }`). */
|
|
23
|
+
hoursOfOperation?: Record<string, string>;
|
|
24
|
+
/** Optional special instructions appended to the agent's instruction bullets. */
|
|
25
|
+
specialInstructions?: string[];
|
|
26
|
+
/** Optional custom welcome message spoken as a non-bargeable static greeting. */
|
|
27
|
+
welcomeMessage?: string;
|
|
28
|
+
/** Agent display name (defaults to `"concierge"`). */
|
|
29
|
+
name?: string;
|
|
30
|
+
/** HTTP route for this agent (defaults to `"/concierge"`). */
|
|
31
|
+
route?: string;
|
|
32
|
+
/** Additional AgentBase options forwarded to `super()`. */
|
|
33
|
+
agentOptions?: Partial<AgentOptions>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ── Agent ───────────────────────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Prefab agent that acts as a virtual concierge for a venue, providing information
|
|
40
|
+
* about services, amenities, hours of operation, availability, and directions.
|
|
41
|
+
*/
|
|
42
|
+
export class ConciergeAgent extends AgentBase {
|
|
43
|
+
/** Name of the venue or business. */
|
|
44
|
+
public venueName: string;
|
|
45
|
+
/** List of services offered by the venue. */
|
|
46
|
+
public services: string[];
|
|
47
|
+
/** Dictionary of amenities, each mapping to a dict of detail keys/values. */
|
|
48
|
+
public amenities: Record<string, Record<string, string>>;
|
|
49
|
+
/** Hours of operation by category. Defaults to `{ default: "9 AM - 5 PM" }`. */
|
|
50
|
+
public hoursOfOperation: Record<string, string>;
|
|
51
|
+
/** Special instructions appended to the agent's instruction bullets. */
|
|
52
|
+
public specialInstructions: string[];
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Create a ConciergeAgent for a venue with the given services, amenities, and hours.
|
|
56
|
+
* @param config - Configuration including venue name, services, amenities, and optional hours/instructions/welcome.
|
|
57
|
+
*/
|
|
58
|
+
constructor(config: ConciergeConfig) {
|
|
59
|
+
const agentName = config.name ?? 'concierge';
|
|
60
|
+
super({
|
|
61
|
+
name: agentName,
|
|
62
|
+
route: config.route ?? '/concierge',
|
|
63
|
+
usePom: true,
|
|
64
|
+
...config.agentOptions,
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// Store configuration
|
|
68
|
+
this.venueName = config.venueName;
|
|
69
|
+
this.services = config.services;
|
|
70
|
+
this.amenities = config.amenities;
|
|
71
|
+
this.hoursOfOperation = config.hoursOfOperation ?? { default: '9 AM - 5 PM' };
|
|
72
|
+
this.specialInstructions = config.specialInstructions ?? [];
|
|
73
|
+
|
|
74
|
+
// Build the agent prompt and settings
|
|
75
|
+
this.setupConciergeAgent(config.welcomeMessage);
|
|
76
|
+
|
|
77
|
+
// Register tools after all fields are initialized
|
|
78
|
+
this.defineTools();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Configure the concierge agent's prompt, hints, params, and global data. */
|
|
82
|
+
private setupConciergeAgent(welcomeMessage?: string): void {
|
|
83
|
+
// Personality
|
|
84
|
+
this.promptAddSection('Personality', {
|
|
85
|
+
body: `You are a professional and helpful virtual concierge for ${this.venueName}.`,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
// Goal
|
|
89
|
+
this.promptAddSection('Goal', {
|
|
90
|
+
body: 'Provide exceptional service by helping users with information, recommendations, and booking assistance.',
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Instructions (base + special)
|
|
94
|
+
const instructions = [
|
|
95
|
+
'Be warm and welcoming but professional at all times.',
|
|
96
|
+
'Provide accurate information about amenities, services, and operating hours.',
|
|
97
|
+
'Offer to help with reservations and bookings when appropriate.',
|
|
98
|
+
'Answer questions concisely with specific, relevant details.',
|
|
99
|
+
...this.specialInstructions,
|
|
100
|
+
];
|
|
101
|
+
this.promptAddSection('Instructions', { bullets: instructions });
|
|
102
|
+
|
|
103
|
+
// Services
|
|
104
|
+
const servicesList = this.services.join(', ');
|
|
105
|
+
this.promptAddSection('Available Services', {
|
|
106
|
+
body: `The following services are available: ${servicesList}`,
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// Amenities (each as a subsection)
|
|
110
|
+
const amenitiesSubsections = Object.entries(this.amenities).map(([name, details]) => ({
|
|
111
|
+
title: this.titleCase(name),
|
|
112
|
+
body: Object.entries(details)
|
|
113
|
+
.map(([k, v]) => `${this.titleCase(k)}: ${v}`)
|
|
114
|
+
.join('\n'),
|
|
115
|
+
}));
|
|
116
|
+
this.promptAddSection('Amenities', {
|
|
117
|
+
body: 'Information about available amenities:',
|
|
118
|
+
subsections: amenitiesSubsections,
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
// Hours of operation
|
|
122
|
+
const hoursList = Object.entries(this.hoursOfOperation)
|
|
123
|
+
.map(([k, v]) => `${this.titleCase(k)}: ${v}`)
|
|
124
|
+
.join('\n');
|
|
125
|
+
this.promptAddSection('Hours of Operation', { body: hoursList });
|
|
126
|
+
|
|
127
|
+
// Post-prompt summary template
|
|
128
|
+
this.setPostPrompt(`
|
|
129
|
+
Return a JSON summary of this interaction:
|
|
130
|
+
{
|
|
131
|
+
"topic": "MAIN_TOPIC",
|
|
132
|
+
"service_requested": "SPECIFIC_SERVICE_REQUESTED_OR_null",
|
|
133
|
+
"questions_answered": ["QUESTION_1", "QUESTION_2"],
|
|
134
|
+
"follow_up_needed": true/false
|
|
135
|
+
}
|
|
136
|
+
`);
|
|
137
|
+
|
|
138
|
+
// Hints for speech recognition
|
|
139
|
+
this.addHints([
|
|
140
|
+
this.venueName,
|
|
141
|
+
...this.services,
|
|
142
|
+
...Object.keys(this.amenities),
|
|
143
|
+
]);
|
|
144
|
+
|
|
145
|
+
// AI behavior params
|
|
146
|
+
this.setParams({
|
|
147
|
+
wait_for_user: false,
|
|
148
|
+
end_of_speech_timeout: 1000,
|
|
149
|
+
ai_volume: 5,
|
|
150
|
+
local_tz: 'America/New_York',
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// Global data
|
|
154
|
+
this.setGlobalData({
|
|
155
|
+
venue_name: this.venueName,
|
|
156
|
+
services: this.services,
|
|
157
|
+
amenities: this.amenities,
|
|
158
|
+
hours: this.hoursOfOperation,
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// Native functions
|
|
162
|
+
this.setNativeFunctions(['check_time']);
|
|
163
|
+
|
|
164
|
+
// Custom welcome message (non-bargeable static greeting)
|
|
165
|
+
if (welcomeMessage) {
|
|
166
|
+
this.setParams({
|
|
167
|
+
static_greeting: welcomeMessage,
|
|
168
|
+
static_greeting_no_barge: true,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
private titleCase(value: string): string {
|
|
174
|
+
// Mirrors Python's str.title(): title-cases each word separated by non-letters.
|
|
175
|
+
return value.replace(/[A-Za-z]+/g, (w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase());
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ── Tool registration ─────────────────────────────────────────────────
|
|
179
|
+
|
|
180
|
+
/** Register the `check_availability` and `get_directions` SWAIG tools. */
|
|
181
|
+
protected override defineTools(): void {
|
|
182
|
+
// Tool: check_availability
|
|
183
|
+
this.defineTool({
|
|
184
|
+
name: 'check_availability',
|
|
185
|
+
description: 'Check availability for a service on a specific date and time',
|
|
186
|
+
parameters: {
|
|
187
|
+
type: 'object',
|
|
188
|
+
properties: {
|
|
189
|
+
service: {
|
|
190
|
+
type: 'string',
|
|
191
|
+
description: 'The service to check (e.g., spa, restaurant)',
|
|
192
|
+
},
|
|
193
|
+
date: {
|
|
194
|
+
type: 'string',
|
|
195
|
+
description: 'The date to check (YYYY-MM-DD format)',
|
|
196
|
+
},
|
|
197
|
+
time: {
|
|
198
|
+
type: 'string',
|
|
199
|
+
description: 'The time to check (HH:MM format, 24-hour)',
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
handler: (args: Record<string, unknown>) => {
|
|
204
|
+
const service = ((args['service'] as string) ?? '').toLowerCase();
|
|
205
|
+
const date = (args['date'] as string) ?? '';
|
|
206
|
+
const time = (args['time'] as string) ?? '';
|
|
207
|
+
|
|
208
|
+
// Simple availability simulation — in a real app this would hit a booking system.
|
|
209
|
+
const lowerServices = this.services.map((s) => s.toLowerCase());
|
|
210
|
+
if (lowerServices.includes(service)) {
|
|
211
|
+
return new FunctionResult(
|
|
212
|
+
`Yes, ${service} is available on ${date} at ${time}. Would you like to make a reservation?`,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
return new FunctionResult(
|
|
216
|
+
`I'm sorry, we don't offer ${service} at ${this.venueName}. ` +
|
|
217
|
+
`Our available services are: ${this.services.join(', ')}.`,
|
|
218
|
+
);
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
// Tool: get_directions
|
|
223
|
+
this.defineTool({
|
|
224
|
+
name: 'get_directions',
|
|
225
|
+
description: 'Get directions to a specific location or amenity',
|
|
226
|
+
parameters: {
|
|
227
|
+
type: 'object',
|
|
228
|
+
properties: {
|
|
229
|
+
location: {
|
|
230
|
+
type: 'string',
|
|
231
|
+
description: 'The location or amenity to get directions to',
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
handler: (args: Record<string, unknown>) => {
|
|
236
|
+
const location = ((args['location'] as string) ?? '').toLowerCase();
|
|
237
|
+
|
|
238
|
+
const amenity = this.amenities[location];
|
|
239
|
+
if (amenity && typeof amenity['location'] === 'string') {
|
|
240
|
+
const amenityLocation = amenity['location'];
|
|
241
|
+
return new FunctionResult(
|
|
242
|
+
`The ${location} is located at ${amenityLocation}. ` +
|
|
243
|
+
`From the main entrance, follow the signs to ${amenityLocation}.`,
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
return new FunctionResult(
|
|
247
|
+
`I don't have specific directions to ${location}. ` +
|
|
248
|
+
'You can ask our staff at the front desk for assistance.',
|
|
249
|
+
);
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ── Lifecycle hooks ───────────────────────────────────────────────────
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Process the interaction summary returned at the end of a call.
|
|
258
|
+
* Logs structured summaries as JSON. Subclasses may override to persist or process.
|
|
259
|
+
*/
|
|
260
|
+
override onSummary(
|
|
261
|
+
summary: Record<string, unknown> | null,
|
|
262
|
+
_rawData: Record<string, unknown>,
|
|
263
|
+
): void | Promise<void> {
|
|
264
|
+
if (summary) {
|
|
265
|
+
try {
|
|
266
|
+
// eslint-disable-next-line no-console
|
|
267
|
+
console.log(`Concierge interaction summary: ${JSON.stringify(summary, null, 2)}`);
|
|
268
|
+
} catch (err) {
|
|
269
|
+
// eslint-disable-next-line no-console
|
|
270
|
+
console.log(`Error processing summary: ${String(err)}`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ── Factory function ────────────────────────────────────────────────────────
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Factory function that creates and returns a new ConciergeAgent.
|
|
280
|
+
* @param config - Configuration for the concierge agent.
|
|
281
|
+
* @returns A configured ConciergeAgent instance.
|
|
282
|
+
*/
|
|
283
|
+
export function createConciergeAgent(config: ConciergeConfig): ConciergeAgent {
|
|
284
|
+
return new ConciergeAgent(config);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export default ConciergeAgent;
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FAQBotAgent - A prefab agent that answers frequently asked questions using
|
|
3
|
+
* keyword/word-overlap matching with configurable similarity thresholds
|
|
4
|
+
* and optional escalation to a live agent.
|
|
5
|
+
*
|
|
6
|
+
* Ported from the Python SDK `signalwire.prefabs.faq_bot.FAQBotAgent`. Keeps
|
|
7
|
+
* TS-specific enhancements (configurable similarity threshold, word-overlap
|
|
8
|
+
* matcher, escalation tool) alongside the Python prefab's public surface.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { AgentBase } from '../AgentBase.js';
|
|
12
|
+
import { FunctionResult } from '../FunctionResult.js';
|
|
13
|
+
import type { AgentOptions } from '../types.js';
|
|
14
|
+
|
|
15
|
+
// ── Config types ────────────────────────────────────────────────────────────
|
|
16
|
+
|
|
17
|
+
export interface FAQEntry {
|
|
18
|
+
/** The representative question text. */
|
|
19
|
+
question: string;
|
|
20
|
+
/** The answer to provide when this FAQ matches. */
|
|
21
|
+
answer: string;
|
|
22
|
+
/** Additional keywords to boost matching accuracy. */
|
|
23
|
+
keywords?: string[];
|
|
24
|
+
/** Taxonomy categories this FAQ belongs to (used for filtering and hints). */
|
|
25
|
+
categories?: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface FAQBotConfig {
|
|
29
|
+
/** Agent display name (defaults to `"faq_bot"`). */
|
|
30
|
+
name?: string;
|
|
31
|
+
/** HTTP route for this agent (defaults to `"/faq"`). */
|
|
32
|
+
route?: string;
|
|
33
|
+
/** List of FAQ entries for the knowledge base. */
|
|
34
|
+
faqs: FAQEntry[];
|
|
35
|
+
/** Whether to suggest related questions alongside a match. Default `true`. */
|
|
36
|
+
suggestRelated?: boolean;
|
|
37
|
+
/** Custom personality description for the agent's "Personality" prompt section. */
|
|
38
|
+
persona?: string;
|
|
39
|
+
/** Minimum match score (0-1) for an FAQ to be considered a match. Default 0.5. */
|
|
40
|
+
threshold?: number;
|
|
41
|
+
/** Message spoken when no FAQ matches the query. */
|
|
42
|
+
escalationMessage?: string;
|
|
43
|
+
/** Phone number to transfer to on escalation. If not set, escalate tool is not registered. */
|
|
44
|
+
escalationNumber?: string;
|
|
45
|
+
/** Additional AgentBase options forwarded to super(). */
|
|
46
|
+
agentOptions?: Partial<AgentOptions>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ── Agent ───────────────────────────────────────────────────────────────────
|
|
50
|
+
|
|
51
|
+
/** Prefab agent that answers frequently asked questions using keyword matching with optional escalation to a live agent. */
|
|
52
|
+
export class FAQBotAgent extends AgentBase {
|
|
53
|
+
/** The configured FAQ entries. */
|
|
54
|
+
public faqs: FAQEntry[];
|
|
55
|
+
/** Whether runner-up FAQ suggestions are appended to matches. */
|
|
56
|
+
public suggestRelated: boolean;
|
|
57
|
+
/** The personality description used in the prompt. */
|
|
58
|
+
public persona: string;
|
|
59
|
+
private threshold: number;
|
|
60
|
+
private escalationMessage: string;
|
|
61
|
+
private escalationNumber: string | null;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Create a FAQBotAgent with the specified FAQ entries and matching threshold.
|
|
65
|
+
* @param config - Configuration including FAQ entries, threshold, and escalation settings.
|
|
66
|
+
*/
|
|
67
|
+
constructor(config: FAQBotConfig) {
|
|
68
|
+
const agentName = config.name ?? 'faq_bot';
|
|
69
|
+
super({
|
|
70
|
+
name: agentName,
|
|
71
|
+
route: config.route ?? '/faq',
|
|
72
|
+
usePom: true,
|
|
73
|
+
...config.agentOptions,
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
this.faqs = config.faqs;
|
|
77
|
+
this.suggestRelated = config.suggestRelated ?? true;
|
|
78
|
+
this.persona =
|
|
79
|
+
config.persona ??
|
|
80
|
+
'You are a helpful FAQ bot that provides accurate answers to common questions.';
|
|
81
|
+
this.threshold = config.threshold ?? 0.5;
|
|
82
|
+
this.escalationMessage =
|
|
83
|
+
config.escalationMessage ??
|
|
84
|
+
"I'm sorry, I couldn't find an answer to your question. Let me transfer you to someone who can help.";
|
|
85
|
+
this.escalationNumber = config.escalationNumber ?? null;
|
|
86
|
+
|
|
87
|
+
this.buildPrompt();
|
|
88
|
+
this.configureAgentSettings();
|
|
89
|
+
|
|
90
|
+
// Register tools after all fields are initialized
|
|
91
|
+
this.defineTools();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ── Prompt construction (mirrors Python _build_faq_bot_prompt) ────────
|
|
95
|
+
|
|
96
|
+
private buildPrompt(): void {
|
|
97
|
+
// Personality
|
|
98
|
+
this.promptAddSection('Personality', { body: this.persona });
|
|
99
|
+
|
|
100
|
+
// Goal
|
|
101
|
+
this.promptAddSection('Goal', {
|
|
102
|
+
body:
|
|
103
|
+
'Answer user questions by matching them to the most similar FAQ in your database.',
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
// Instructions
|
|
107
|
+
const instructions = [
|
|
108
|
+
'Compare user questions to your FAQ database and find the best match.',
|
|
109
|
+
'Provide the answer from the FAQ database for the matching question.',
|
|
110
|
+
'If no close match exists, politely say you don\'t have that information.',
|
|
111
|
+
'Be concise and factual in your responses.',
|
|
112
|
+
];
|
|
113
|
+
if (this.suggestRelated) {
|
|
114
|
+
instructions.push(
|
|
115
|
+
'When appropriate, suggest other related questions from the FAQ database that might be helpful.',
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
this.promptAddSection('Instructions', { bullets: instructions });
|
|
119
|
+
|
|
120
|
+
// FAQ Database (each FAQ as a subsection with optional categories line)
|
|
121
|
+
const faqSubsections = this.faqs
|
|
122
|
+
.filter((faq) => faq.question && faq.answer)
|
|
123
|
+
.map((faq) => {
|
|
124
|
+
let body = faq.answer;
|
|
125
|
+
if (faq.categories && faq.categories.length > 0) {
|
|
126
|
+
body = `${body}\n\nCategories: ${faq.categories.join(', ')}`;
|
|
127
|
+
}
|
|
128
|
+
return { title: faq.question, body };
|
|
129
|
+
});
|
|
130
|
+
this.promptAddSection('FAQ Database', {
|
|
131
|
+
body: 'Here is your database of frequently asked questions and answers:',
|
|
132
|
+
subsections: faqSubsections,
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
if (this.suggestRelated) {
|
|
136
|
+
this.promptAddSection('Related Questions', {
|
|
137
|
+
body:
|
|
138
|
+
'When appropriate, suggest other related questions from the FAQ database that might be helpful.',
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ── Agent settings (mirrors Python _configure_agent_settings + _setup_post_prompt) ─
|
|
144
|
+
|
|
145
|
+
private configureAgentSettings(): void {
|
|
146
|
+
// Post-prompt summary template
|
|
147
|
+
this.setPostPrompt(`
|
|
148
|
+
Return a JSON summary of this interaction:
|
|
149
|
+
{
|
|
150
|
+
"question": "MAIN_QUESTION_ASKED",
|
|
151
|
+
"matched_faq": "MATCHED_FAQ_QUESTION_OR_null",
|
|
152
|
+
"answered_successfully": true/false,
|
|
153
|
+
"suggested_related": []
|
|
154
|
+
}
|
|
155
|
+
`);
|
|
156
|
+
|
|
157
|
+
// Hints: 4+ char question words, FAQ keywords, and categories
|
|
158
|
+
const hints: string[] = [];
|
|
159
|
+
for (const faq of this.faqs) {
|
|
160
|
+
const question = faq.question ?? '';
|
|
161
|
+
if (question) {
|
|
162
|
+
const words = question
|
|
163
|
+
.split(/\s+/)
|
|
164
|
+
.map((w) => w.replace(/^[.,?!]+|[.,?!]+$/g, ''))
|
|
165
|
+
.filter((w) => w.length >= 4);
|
|
166
|
+
hints.push(...words);
|
|
167
|
+
}
|
|
168
|
+
if (faq.keywords) hints.push(...faq.keywords);
|
|
169
|
+
if (faq.categories) hints.push(...faq.categories);
|
|
170
|
+
}
|
|
171
|
+
const unique = Array.from(new Set(hints));
|
|
172
|
+
if (unique.length > 0) this.addHints(unique);
|
|
173
|
+
|
|
174
|
+
// AI behavior parameters
|
|
175
|
+
this.setParams({
|
|
176
|
+
wait_for_user: false,
|
|
177
|
+
end_of_speech_timeout: 1000,
|
|
178
|
+
ai_volume: 5,
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
// Global data: faq count and categories
|
|
182
|
+
const categories = Array.from(
|
|
183
|
+
new Set(
|
|
184
|
+
this.faqs.flatMap((faq) => faq.categories ?? []),
|
|
185
|
+
),
|
|
186
|
+
);
|
|
187
|
+
this.setGlobalData({
|
|
188
|
+
faq_count: this.faqs.length,
|
|
189
|
+
categories,
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
// Native functions
|
|
193
|
+
this.setNativeFunctions(['check_time']);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ── Matching engine ───────────────────────────────────────────────────
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Compute a word-overlap similarity score between a query and an FAQ entry.
|
|
200
|
+
* Combines question text similarity and keyword overlap.
|
|
201
|
+
* Returns a value between 0 and 1.
|
|
202
|
+
*/
|
|
203
|
+
private computeMatchScore(query: string, faq: FAQEntry): number {
|
|
204
|
+
const queryWords = this.tokenize(query);
|
|
205
|
+
if (queryWords.length === 0) return 0;
|
|
206
|
+
|
|
207
|
+
// Score against the question text
|
|
208
|
+
const questionWords = this.tokenize(faq.question);
|
|
209
|
+
const questionOverlap = this.wordOverlap(queryWords, questionWords);
|
|
210
|
+
|
|
211
|
+
// Score against keywords
|
|
212
|
+
let keywordScore = 0;
|
|
213
|
+
if (faq.keywords && faq.keywords.length > 0) {
|
|
214
|
+
const keywordTokens = faq.keywords.map((k) => k.toLowerCase().trim());
|
|
215
|
+
const queryLower = query.toLowerCase();
|
|
216
|
+
let keywordHits = 0;
|
|
217
|
+
for (const kw of keywordTokens) {
|
|
218
|
+
if (queryLower.includes(kw)) {
|
|
219
|
+
keywordHits++;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
keywordScore = keywordTokens.length > 0 ? keywordHits / keywordTokens.length : 0;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Weighted combination: 60% question overlap, 40% keyword score
|
|
226
|
+
return faq.keywords && faq.keywords.length > 0
|
|
227
|
+
? questionOverlap * 0.6 + keywordScore * 0.4
|
|
228
|
+
: questionOverlap;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
private tokenize(text: string): string[] {
|
|
232
|
+
return text
|
|
233
|
+
.toLowerCase()
|
|
234
|
+
.replace(/[^a-z0-9\s]/g, ' ')
|
|
235
|
+
.split(/\s+/)
|
|
236
|
+
.filter((w) => w.length > 1 && !STOP_WORDS.has(w));
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
private wordOverlap(queryWords: string[], targetWords: string[]): number {
|
|
240
|
+
if (queryWords.length === 0 || targetWords.length === 0) return 0;
|
|
241
|
+
const targetSet = new Set(targetWords);
|
|
242
|
+
let matches = 0;
|
|
243
|
+
for (const word of queryWords) {
|
|
244
|
+
if (targetSet.has(word)) matches++;
|
|
245
|
+
}
|
|
246
|
+
// Normalize by the smaller set to be lenient
|
|
247
|
+
const divisor = Math.min(queryWords.length, targetWords.length);
|
|
248
|
+
return divisor > 0 ? matches / divisor : 0;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ── Tool registration ─────────────────────────────────────────────────
|
|
252
|
+
|
|
253
|
+
/** Register the search_faqs and optional escalate SWAIG tools. */
|
|
254
|
+
protected override defineTools(): void {
|
|
255
|
+
// Tool: search_faqs (matches Python name; supports optional category filter)
|
|
256
|
+
this.defineTool({
|
|
257
|
+
name: 'search_faqs',
|
|
258
|
+
description: 'Search for FAQs matching a specific query or category',
|
|
259
|
+
parameters: {
|
|
260
|
+
type: 'object',
|
|
261
|
+
properties: {
|
|
262
|
+
query: {
|
|
263
|
+
type: 'string',
|
|
264
|
+
description: 'The search query',
|
|
265
|
+
},
|
|
266
|
+
category: {
|
|
267
|
+
type: 'string',
|
|
268
|
+
description: 'Optional category to filter by',
|
|
269
|
+
},
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
handler: (args: Record<string, unknown>) => {
|
|
273
|
+
const query = (args['query'] as string) ?? '';
|
|
274
|
+
const category = ((args['category'] as string) ?? '').toLowerCase().trim();
|
|
275
|
+
if (!query) {
|
|
276
|
+
return new FunctionResult('A query is required to search the FAQ.');
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Optionally filter by category
|
|
280
|
+
const pool = category
|
|
281
|
+
? this.faqs.filter(
|
|
282
|
+
(faq) =>
|
|
283
|
+
(faq.categories ?? []).some((c) => c.toLowerCase().trim() === category),
|
|
284
|
+
)
|
|
285
|
+
: this.faqs;
|
|
286
|
+
|
|
287
|
+
if (pool.length === 0) {
|
|
288
|
+
return new FunctionResult('No matching FAQs found.');
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Score all FAQs in the (possibly filtered) pool
|
|
292
|
+
const scored = pool
|
|
293
|
+
.map((faq) => ({ faq, score: this.computeMatchScore(query, faq) }))
|
|
294
|
+
.filter((s) => s.score >= this.threshold)
|
|
295
|
+
.sort((a, b) => b.score - a.score);
|
|
296
|
+
|
|
297
|
+
if (scored.length === 0) {
|
|
298
|
+
return new FunctionResult('No matching FAQs found.');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Match Python's response format: a numbered list of the top 3 matches'
|
|
302
|
+
// question text (faq_bot.py:276-283). The answer text is supplied to
|
|
303
|
+
// the AI via the prompt's "FAQ Database" section — the tool just
|
|
304
|
+
// indicates which FAQs matched. The `suggest_related` flag does not
|
|
305
|
+
// change the top-N here; it only toggles the prompt's "Related
|
|
306
|
+
// Questions" section and the extra instruction bullet (Python parity).
|
|
307
|
+
const top = scored.slice(0, 3);
|
|
308
|
+
const lines = top.map((s, i) => `${i + 1}. ${s.faq.question}`).join('\n');
|
|
309
|
+
return new FunctionResult(`Here are the most relevant FAQs:\n\n${lines}\n`);
|
|
310
|
+
},
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
// Tool: escalate (only if escalation number is configured)
|
|
314
|
+
if (this.escalationNumber) {
|
|
315
|
+
this.defineTool({
|
|
316
|
+
name: 'escalate',
|
|
317
|
+
description: 'Transfer the caller to a live agent when the FAQ knowledge base cannot answer their question.',
|
|
318
|
+
parameters: {
|
|
319
|
+
type: 'object',
|
|
320
|
+
properties: {
|
|
321
|
+
reason: {
|
|
322
|
+
type: 'string',
|
|
323
|
+
description: 'The reason for escalation.',
|
|
324
|
+
},
|
|
325
|
+
},
|
|
326
|
+
},
|
|
327
|
+
handler: (_args: Record<string, unknown>) => {
|
|
328
|
+
const reason = (_args['reason'] as string) || 'Caller needs assistance beyond FAQ';
|
|
329
|
+
const result = new FunctionResult(
|
|
330
|
+
`${this.escalationMessage} Transferring caller to a live agent. Reason: ${reason}`,
|
|
331
|
+
);
|
|
332
|
+
result.connect(this.escalationNumber!);
|
|
333
|
+
return result;
|
|
334
|
+
},
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ── Lifecycle hooks ───────────────────────────────────────────────────
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Process the interaction summary returned at the end of a call.
|
|
343
|
+
* Logs structured summaries as JSON. Subclasses may override to persist or process.
|
|
344
|
+
*/
|
|
345
|
+
override onSummary(
|
|
346
|
+
summary: Record<string, unknown> | null,
|
|
347
|
+
_rawData: Record<string, unknown>,
|
|
348
|
+
): void | Promise<void> {
|
|
349
|
+
if (summary) {
|
|
350
|
+
try {
|
|
351
|
+
// eslint-disable-next-line no-console
|
|
352
|
+
console.log(`FAQ interaction summary: ${JSON.stringify(summary, null, 2)}`);
|
|
353
|
+
} catch (err) {
|
|
354
|
+
// eslint-disable-next-line no-console
|
|
355
|
+
console.log(`Error processing summary: ${String(err)}`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ── Common English stop words filtered from matching ────────────────────────
|
|
362
|
+
|
|
363
|
+
const STOP_WORDS = new Set([
|
|
364
|
+
'a', 'an', 'the', 'is', 'it', 'to', 'in', 'of', 'and', 'or', 'for',
|
|
365
|
+
'on', 'at', 'by', 'do', 'if', 'my', 'so', 'up', 'am', 'as', 'be',
|
|
366
|
+
'he', 'me', 'we', 'no', 'not', 'are', 'was', 'has', 'had', 'how',
|
|
367
|
+
'its', 'can', 'did', 'get', 'but', 'you', 'her', 'him', 'his', 'she',
|
|
368
|
+
'our', 'who', 'this', 'that', 'what', 'with', 'have', 'from', 'will',
|
|
369
|
+
'your', 'they', 'them', 'been', 'does', 'just', 'than', 'when', 'which',
|
|
370
|
+
'would', 'could', 'should', 'about', 'their', 'there', 'these', 'those',
|
|
371
|
+
]);
|
|
372
|
+
|
|
373
|
+
// ── Factory function ────────────────────────────────────────────────────────
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* Factory function that creates and returns a new FAQBotAgent.
|
|
377
|
+
* @param config - Configuration for the FAQ bot agent.
|
|
378
|
+
* @returns A configured FAQBotAgent instance.
|
|
379
|
+
*/
|
|
380
|
+
export function createFAQBotAgent(config: FAQBotConfig): FAQBotAgent {
|
|
381
|
+
return new FAQBotAgent(config);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
export default FAQBotAgent;
|