TalkyJS Core Documentation

website·Indexed 29 days ago

https://talkyjs.github.io/talkyjs-core/

Technical documentation for @talkyjs/core, featuring API references for skill management, session and persistent attribute managers, routing, and user activity tracking. Includes details on classes such as SkillFactory, RouteMatcher, and SituationService, as well as interfaces for TalkyJSAPIClientConfig and TalkyJSSkillConfig.

Tokens
11.5K
Snippets
82
Records
94
Agent score
72%

What's inside TalkyJS

  1. Use SessionAttributesManager to manage prefixed session attributes

    The SessionAttributesManager is an abstract class used to manage session attributes within the @talkyjs/core framework. It ensures that attributes are stored under a specific namespace (default prefix __talkyjs) to prevent collisions with other session data. It requires an AttributesManager (from ask-sdk-core) to be passed into its constructor.
    import { AttributesManager } from 'ask-sdk-core';
    import { SessionAttributesManager } from '@talkyjs/core';
    
    class MySessionManager extends SessionAttributesManager {
      // Implementation
    }
    
    const manager = new MySessionManager({
      attributesManager: myAttributesManagerInstance
    });
  2. Manage session state and turn counts with SessionSituationService

    The SessionSituationService class extends SessionAttributesManager to track and update the current state and turn count of a user session. It stores this data in the session attributes under the key sessionSituation.
    import { SessionSituationService } from '@talkyjs/core';
    
    // Initialize with required HandlerInput properties
    const situationService = new SessionSituationService({
      attributesManager: handlerInput.attributesManager,
      requestEnvelope: handlerInput.requestEnvelope
    });
  3. Manage skill configuration using the SkillConfig class

    The SkillConfig class provides a singleton manager for handling TalkyJSSkillConfig. It ensures that configuration properties are initialized with defaults and allows for dynamic updates to the configuration instance.
  4. Use RouteMatcher to determine if a route should handle a request

    The RouteMatcher class is used to evaluate whether a Router configuration matches the current HandlerInput. It checks several criteria in sequence: request type, intent name (for intent requests), situation constraints (state, invocation count, and turn count), and finally any custom matching logic defined in the route's situation.
    import { RouteMatcher } from '@talkyjs/core';
    
    // Initialize with handler input and the target route configuration
    const matcher = new RouteMatcher(input, targetRoute);
    
    // Execute the matching logic
    await matcher.match();
    
    // Check if the route is a match
    const isMatch = matcher.getMatchResult();
  5. Handle localized error responses with ErrorHandlerService

    The ErrorHandlerService provides a centralized way to manage and retrieve localized error messages (speak and reprompt strings) based on the user's locale. It includes logic to match requested locales against supported languages and defaults to English if no match is found.
    import { ErrorHandlerService } from '@talkyjs/core';
    
    // Get the error response for a specific request input
    const response = ErrorHandlerService.getResponse(input);
    console.log(response.speak); // e.g., 'Sorry I could not understand...'
  6. Manage conversation state with SituationService

    The SituationService class provides a high-level API to track and manipulate the current 'situation' of a conversation. It synchronizes state between the session and persistent storage (via UserActivityManager). It is used to track turn counts, current states, and invocation details.
    import { SituationService } from '@talkyjs/core';
    
    // Initialize with required HandlerInput properties
    const situationService = new SituationService({
      attributesManager: attributesManager,
      requestEnvelope: requestEnvelope
    });
  7. Use RepeatIntentService to manage session response history

    The RepeatIntentService class (extending SessionAttributesManager) provides a mechanism to store and retrieve the most recent response in a user session. This is typically used to implement 'repeat' functionality where the system re-plays the last sent message.
    import { RepeatIntentService } from '@talkyjs/core';
    
    // Example usage
    const repeatService = new RepeatIntentService();
    
    // Save a response
    repeatService.recordResponse(currentResponse);
    
    // Check if a response exists and load it
    if (repeatService.hasLastResponse()) {
      const lastResponse = repeatService.loadLastResponse();
    }
  8. Manage persistent attributes with PersistentAttributesManager

    The PersistentAttributesManager is a wrapper for the ask-sdk-core AttributesManager. It provides a simplified interface to get, update, and save persistent attributes for a user session. It supports generics to define the shape of the persistent attributes via the PersistentAttributes interface.
    import { PersistentAttributesManager } from '@talkyjs/core';
    
    // Example attribute shape
    interface UserAttributes {
      name: string;
      age: number;
    }
    
    // Get instance using the handlerInput.attributesManager from Alexa SDK
    const manager = PersistentAttributesManager.getInstance<UserAttributes>(handlerInput.attributesManager);
  9. Update and persist attributes with updatePersistentAttributes and save

    Updating attributes is a two-step process:

    1. Call updatePersistentAttributes(attributes) to merge new values into the current session state.
    2. Call save() to commit those changes to the persistent storage. The save() method only executes the underlying SDK save operation if changes have actually occurred.
    await persistentAttributesManager.updatePersistentAttributes({ key: 'value' });
    await persistentAttributesManager.save();
  10. Use RequestHandlerFactory to generate Alexa RequestHandlers

    The RequestHandlerFactory class is used to transform Router definitions into standard Alexa SDK RequestHandler objects. It allows developers to define routing logic and automatically generate the canHandle and handle methods required by the Alexa SDK. The factory also supports automatic session termination if the route's situation specifies shouldEndSession.
    import { RequestHandlerFactory } from '@talkyjs/core';
    import { Router } from '@talkyjs/core/model';
    
    const factory = new RequestHandlerFactory();
    
    // Add one or more router configurations
    factory.addRoutes(myRouter1, myRouter2);
    
    // Generate an array of RequestHandlers to be passed to the Alexa SDK app
    const handlers = factory.createHandlers();
  11. Initialize and launch a SkillFactory instance

    Use the SkillFactory.launch(config) method to create or retrieve a singleton instance of the factory. The factory handles the loading of configuration via SkillConfig and initializes the underlying CustomSkillBuilder with the provided skill ID, log levels, and error handlers.
    import { SkillFactory } from '@talkyjs/core';
    
    const factory = SkillFactory.launch({
      // TalkyJSSkillConfig options
      stage: 'development',
      logLevel: 'info',
      skillId: 'amzn1.ask.skill.xxx'
    });
  12. Manage persistent attributes with PersistentAttributesManager

    The PersistentAttributesManager is a wrapper for the ask-sdk-core AttributesManager. It provides a simplified interface for retrieving, updating, and saving persistent attributes. It implements a singleton pattern via getInstance and ensures that updates are merged with existing data.
    import { AttributesManager } from 'ask-sdk-core';
    import { PersistentAttributesManager } from '@talkyjs/core';
    
    // Get singleton instance
    const persistentAttributesManager = PersistentAttributesManager.getInstance(handlerInput.attributesManager);
    
    // Update attributes (merges with existing)
    await persistentAttributesManager.updatePersistentAttributes({
        name: 'John'
    });
    
    // IMPORTANT: Must call save() to persist changes to the cloud
    await persistentAttributesManager.save();