Introduction to node-wit
node-wit is a powerful library that provides an interface to use Wit.ai, an NLP (Natural Language Processing) platform that makes it easy to build applications with highly interactive conversational capabilities. Using node-wit, developers can seamlessly integrate Wit.ai’s advanced natural language processing functionalities into their Node.js applications.
Getting Started with node-wit
const { Wit, log } = require('node-wit'); const client = new Wit({ accessToken: 'YOUR_WIT_AI_ACCESS_TOKEN' });
API Examples
Making Sense of User Input
node-wit can analyze the intent and entities from a given message:
client.message('What is the weather like in New York?', {}) .then((data) => { console.log('Yay, got Wit.ai response: ' + JSON.stringify(data)); }) .catch(console.error);
Extracting Entities
You can extract specific entities from user messages, such as locations, dates, and more:
client.message('Schedule a meeting on next Monday', {}) .then((data) => { const entities = data.entities; const datetime = entities['wit$datetime:datetime'] ? entities['wit$datetime:datetime'][0].value : 'Not found'; console.log('The meeting is scheduled on: ' + datetime); }) .catch(console.error);
Running Actions
Running custom actions defined in your Wit.ai app to handle more sophisticated conversations:
const actions = { send(request, response) { const { text, quickreplies } = response; console.log('sending...', JSON.stringify(response)); }, myAction(request) { return new Promise(function(resolve, reject) { console.log('executing myAction'); return resolve(); }); }, }; const client = new Wit({ accessToken: 'YOUR_WIT_AI_ACCESS_TOKEN', actions });
Tracking Conversations
Using the conversation API to maintain the context of a conversation:
const sessionId = 'my-user-1234'; client.converse(sessionId, 'I want to order pizza', {}) .then((data) => { console.log('Got Wit.ai response: ' + JSON.stringify(data)); }) .catch(console.error);
Complete App Example
Here’s a more complete example of a Node.js application using node-wit to create a simple chatbot:
const express = require('express'); const bodyParser = require('body-parser'); const { Wit, log } = require('node-wit'); const app = express(); const client = new Wit({ accessToken: 'YOUR_WIT_AI_ACCESS_TOKEN' }); app.use(bodyParser.json()); app.post('/webhook', (req, res) => { const { message, sessionId } = req.body; client.converse(sessionId, message, {}) .then((data) => { res.json(data); }) .catch((err) => { console.error(err); res.status(500).send('Something went wrong!'); }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
With node-wit, building conversational AI applications becomes straightforward and efficient.
Hash: ba56a19fdc7c835f3c0252f17cc65c7f870d9116744a21f545f788f78bc01980