Introduction to Node-Wit
Node-Wit is a powerful Node.js library that allows developers to integrate Wit.ai’s natural language processing (NLP) capabilities into their applications. This enables the creation of highly interactive and intelligent conversational experiences.
Getting Started
To get started with Node-Wit, you’ll need to install the package using npm:
npm install node-wit
APIs and Code Snippets
1. Importing and Initializing Wit Client
const { Wit, log } = require('node-wit'); const client = new Wit({ accessToken: 'YOUR_ACCESS_TOKEN', logger: new log.Logger(log.DEBUG) });
2. Sending Text Messages to Wit
client.message('Hello, how are you?', {}) .then(data => { console.log('Wit response: ', data); }) .catch(console.error);
3. Managing Sessions
let sessions = {}; const findOrCreateSession = (userId) => { let sessionId; Object.keys(sessions).forEach(k => { if (sessions[k].userId === userId) { sessionId = k; } }); if (!sessionId) { sessionId = new Date().toISOString(); sessions[sessionId] = {userId: userId, context: {}}; } return sessionId; }
4. Sending Actions
const actions = { send(request, response) { const {sessionId, context, entities, text} = request; return new Promise(function(resolve, reject) { console.log('User said: ', text); console.log('Wit response: ', response.text); return resolve(); }); }, findAnswer({context, entities}) { return new Promise(function(resolve, reject) { context.answer = 'This is the answer from findAnswer function!'; return resolve(context); }); } }; const clientWithActions = new Wit({ accessToken: 'YOUR_ACCESS_TOKEN', actions });
Complete App Example
const { Wit, log } = require('node-wit'); const readline = require('readline'); const client = new Wit({ accessToken: 'YOUR_ACCESS_TOKEN', logger: new log.Logger(log.DEBUG) }); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.setPrompt('You: '); rl.prompt(); rl.on('line', (line) => { client.message(line, {}) .then((data) => { console.log('Wit: ', data); rl.prompt(); }) .catch((err) => { console.error('Error: ', err); rl.prompt(); }); }).on('close', () => { console.log('Bye!'); process.exit(0); });
With the above example, you can interact with Wit.ai directly from your command line, allowing you to test your conversational AI skills quickly and efficiently.
Hash: ba56a19fdc7c835f3c0252f17cc65c7f870d9116744a21f545f788f78bc01980