npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

imago-pni-client

v2.24.5

Published

Client library for easy access to Imago.ai's Preprocessor and NLP Interface (PNI).

Downloads

14

Readme

Imago PNI Client

A client library that provides easy access to Imago.ai's Preprocessor and NLP Engine Interface (PNI).

Installation

npm i --save imago-pni-client

The client requires at least Node 7.6.0; recommended Node 8.9 and above.

Usage - Recognizing sentences

In order to use the client, you need to obtain a license key from Imago.

async ask(text)

This is the main function that uses Natural Language Processing to understand the user's message.

// Set up:
const ImagoPniClient = require('imago-pni-client');
const IMAGO_PNI_KEY = 'e379341be40d46348c4c352523ecb33e';

// Call the Web API - must be inside an async function.
async function askImago() {
  const client = new ImagoPniClient({
    licenseKey: IMAGO_PNI_KEY,
    convoId: 'test-conversation-1',
  });
  let response = await client.ask('Hey there!');
}

askImago();

async getQuota()

Returns the total quota granted for your license and the amount of quota used up.

The data is refreshed once in 10 minutes.

// Set up:
const ImagoPniClient = require('imago-pni-client');
const IMAGO_PNI_KEY = 'e379341be40d46348c4c352523ecb33e';

// Call the Web API - must be inside an async function.
async function printQuota() {
  const client = new ImagoPniClient({
    licenseKey: IMAGO_PNI_KEY,
    convoId: 'test-conversation-1',
  });
  const response = await client.getQuota();
  const percentageUsed = ((response.data.used / response.data.quota) * 100).toFixed(2);
  console.log(`Used ${response.data.used}/${response.data.quota} messages (${percentageUsed}%)`);
}

printQuota();

async clearContext()

This function rarely needs to be used; it clears the context information stored by the PNI. This information helps the NLP engine understand at which step of the dialog the user is located, and may also contain context variables, something similar to browser cookies.

The context is saved separately for each conversation ID.

const ImagoPniClient = require('imago-pni-client');
const IMAGO_PNI_KEY = 'e379341be40d46348c4c352523ecb33e';

async function resetContext() {
    const client = new ImagoPniClient({
        licenseKey: IMAGO_PNI_KEY,
        convoId: 'test-conversation-1',
    });

    let success = await client.clearContext();
    if (success) {
        console.log('Context information deleted.');
    } else {
        console.log('There was an error removing context information.');
    }
}

resetContext();

async getContext()

Get context variables on the PNI server.

const ImagoPniClient = require('imago-pni-client');
const IMAGO_PNI_KEY = 'e379341be40d46348c4c352523ecb33e';
const client = new ImagoPniClient({
  licenseKey: IMAGO_PNI_KEY,
  convoId: 'test-conversation-1',
  server: ImagoPniClient.selectServer('dev'),
});
  const result = await client.getContext();

async updateContext(updatedVariables)

Update context variables on the PNI server. The properties in the updatedVariables will be replaced with these values; other context data will not be updated.

The maximum supported data amount is around 20KB. Do not updated big chunks of context data with this method.

const ImagoPniClient = require('imago-pni-client');
const IMAGO_PNI_KEY = 'e379341be40d46348c4c352523ecb33e';

async function setUserNameAndAge(name, age) {
    const client = new ImagoPniClient({
        licenseKey: IMAGO_PNI_KEY,
        convoId: 'test-conversation-1',
    });

    try {
        await client.updateContext({
            userName: name,
            userAge: age,
        });
    } catch (error) {
        console.log('Error updating context: ', error);
    }
}

setUserNameAndAge('Test', 20);

Initalization options

When creating a new instance of the ImagoPniClient, you can pass the following options:

  • licenseKey - required. The license key you obtained from Imago.
  • convoId - required. An arbitrary conversation ID that helps you track the conversation. It must be the same for conversations with the same user. For example, you can use the Facebook ID of the user who is talking to the bot.
  • server - optional. The server running Imago PNI software. See ImagoPniClient.servers for the list.
  • apiVerion - optional. The version level of the Imago PNI API. Default is 'v1'.
  • includeRawResponse - optional. Whether to attach the original NLP engine's response to the returned data. This can be useful for examining the data returned by the NLP engine in more details.
  • logger - optional. A logging function. Default: console.log.

Servers

There are three available servers for the PNI. The default is the production server. The list of servers is stored inside ImagoPniClient.servers. Example initialization with a specific server name:

const ImagoPniClient = require('imago-pni-client');
const IMAGO_PNI_KEY = 'e379341be40d46348c4c352523ecb33e';

let client1 = new ImagoPniClient({
    server: ImagoPniClient.servers.UAT,
    licenseKey: IMAGO_PNI_KEY,
    convoId: 'test-conversation-1',
});

let client2 = new ImagoPniClient({
    server: ImagoPniClient.servers.DEVELOPMENT,
    licenseKey: IMAGO_PNI_KEY,
    convoId: 'test-conversation-1',
});

let client3 = new ImagoPniClient({
    server: ImagoPniClient.servers.PRODUCTION, // this is default
    licenseKey: IMAGO_PNI_KEY,
    convoId: 'test-conversation-1',
});

let client4 = new ImagoPniClient({
    server: ImagoPniClient.servers.LOCALHOST, // http://localhost:3000
    licenseKey: IMAGO_PNI_KEY,
    convoId: 'test-conversation-1',
});

let client5 = new ImagoPniClient({
    server: 'example.com', // if any other server becomes available
    licenseKey: IMAGO_PNI_KEY,
    convoId: 'test-conversation-1',
});

Selecting the server automatically

You can select the server automatically based on your environment type. The method static selectServer(environment) takes the environment type string (for example, "LOCALHOST", "local", "DEV", "development", "UAT", "prod", "production") and returns the appropriate server type.

let environment = process.env.NODE_ENV; // 'production'

let client = new ImagoPniClient({
    server: ImagoPniClient.selectServer(environment),
    // other initialization parameters
});

Response format

The response format is EIF (Engine Independent Format).

It includes the originalQuery, rawOriginalQuery, topIntent, topIntentScore, intents[], entities[], answer (for IBM Watson Conversation only), and the original NLP engine's response under raw.

The difference between originalQuery and rawOriginalQuery is that the former is the message sent to the NLP engine (perhaps modified by our preprocessor), and the rawOriginalQuery is the exact text sent by the user (before any preprocessing).

Example of an EIF response:

{
  "originalQuery": "hey there!",
  "rawOriginalQuery": "hey there!",
  "topIntent": "Greetings",
  "topIntentScore": 0.9852514743804932,
  "intents": [
    {
      "intent": "Greetings",
      "confidence": 0.9852514743804932
    }
  ],
  "entities": [
    {
      "type": "greeting",
      "value": "hi",
      "location": [0, 2],
    }
  ],
  "answer": "Hi! I'm a bot, nice talking to you.",
  "raw": {
    "intents": [
      {
        "intent": "Greetings",
        "confidence": 0.9852514743804932
      }
    ],
    "entities": [{
      "entity": "greeting",
      "location": [0, 2],
      "value": "hi",
      "confidence": 1
    }],
    "input": {
      "text": "hey there"
    },
    "output": {
      "text": [
        "Hi! I'm a bot, nice talking to you."
      ],
      "nodes_visited": [
        "Welcome"
      ],
      "log_messages": [
        
      ]
    },
    "context": {
      "conversation_id": "c3924ae7-9e4c-441f-b2ff-fec70d3bc9ad",
      "system": {
        "dialog_stack": [
          {
            "dialog_node": "root"
          }
        ],
        "dialog_turn_counter": 1,
        "dialog_request_counter": 1,
        "_node_output_map": {
          "node_16_1503017179283": [
            0
          ]
        },
        "branch_exited": true,
        "branch_exited_reason": "completed"
      }
    }
  },
  "elapsed": "125 ms, including 16 ms for the NLP engine."
}

Usage - Importing data into the NLP engine

async importApp(options)

The PNI client can also be used to import the bot training data from the SQL database into the NLP engine.

To do that, you need to first fetch the data from four tables in SQL, and then call the PNI client as follows:

const ImagoPniClient = require('imago-pni-client');
const IMAGO_PNI_KEY = 'e379341be40d46348c4c352523ecb33e';

async function importApp() {
    const client = new ImagoPniClient({
        licenseKey: IMAGO_PNI_KEY,
        convoId: 'test-conversation-1',
    });

    // This function should be written by you and return an array of four items,
    // each of which represents all rows from one of the four SQL tables:
    let [intents, utterances, entityTypes, entities] = await fetchDataFromSql();

    let jobId = await client.importApp({
        appLanguage: 'en',
        intents, utterances, entityTypes, entities,
    });

    // This jobId is returned before the import job is completed. The frontend
    // or backend can then use this jobId to check for the job status using
    // another endpoint.
    return jobId;
}

importApp();

async checkJobStatus(jobId)

The async importApp() function returns a jobId that can be used to check the status of the import job. The job typically takes from 10 seconds to 2 minutes.

You can check the status of the job to view the status messages and check whether it is completed.

The response contains three properties: success, log and done. success being equal to true means that the job status was fetched successful. The log contains the text of the log as string. If done is true, that means the job has completed.

// This should have been obtained from the importApp() function:
const jobId = '70ae5e08-fc75-46ee-8bc7-67a0d63badd6';

// licenseKey and convoId can be set to any non-empty string, e.g. 'not required',
// because the endpoint for checking the job status does not require a license
// or a conversation ID.
const client = new ImagoPniClient({
    licenseKey: IMAGO_PNI_KEY,
    convoId: 'test-conversation-1',
});

// Make request to server to fetch job status:
let response = await client.checkJobStatus(jobId);

// Output results to console:
if (response && response.success) {
    if (response.done) {
        console.log(`Job completed!`);
    } else {
        console.log(response.log);
    }
} else {
    console.log('Failed to check job status.');
}

Usage - Utterance Requests

Customer can request to add a new utterance to the training data. To create and manage the requests, use the methods below:

async requestNewUtterance(utterance)

Sends a request to Imago to add a new utterance (sentence) to the training data set.

The utterance is an arbitrary object containing at least a text property.

await client.requestNewUtterance({
	text: 'Hey there', // this is required
	intent: 'Greeting', // an arbitrary optional field
	requestedBy: '[email protected]', // an arbitrary optional field
});

async getAllUtteranceRequests()

async getCompletedUtteranceRequests()

async getPendingUtteranceRequests()

Returns all utterance requests for the given license key (the first method), or only completed or only pending requests (the other two methods).

The return value is an array of objects, each of which represents an utterance request.

async cancelPendingUtteranceRequest(id)

Cancels a pending utterance request if it hasn't been completed yet.

The id is the value of the RowKey property that you can get from inside the utterance request object by using one of the three get... methods above.

const allPendingRequests = await client.getPendingUtteranceRequests();

// Cancel all pending requests:
for (const r of allPendingRequests) {
  // For better performance, we are not awaiting this
  // function here:
  client.cancelPendingUtteranceRequest(r.RowKey);
}