Examples

Real-world examples showing how to use semantic-node-router in production applications

🎧

1. Customer Support Routing

Route support tickets to the appropriate department based on semantic understanding.

customer-support.ts
1import { Router, Route, OpenAIEncoder } from 'semantic-node-router';
2
3// Define customer support routes
4const routes = [
5  new Route({
6    name: 'billing',
7    utterances: [
8      'payment issue',
9      'charged twice',
10      'subscription',
11      'invoice not received',
12      'cancel my subscription',
13      'billing question'
14    ]
15  }),
16  new Route({
17    name: 'technical_support',
18    utterances: [
19      'app crashed',
20      'error message',
21      'not working',
22      'bug report',
23      'can\'t log in',
24      'performance issue'
25    ]
26  }),
27  new Route({
28    name: 'account',
29    utterances: [
30      'reset password',
31      'change email',
32      'delete my account',
33      'update profile',
34      'security settings'
35    ]
36  }),
37  new Route({
38    name: 'shipping',
39    utterances: [
40      'where is my order',
41      'track package',
42      'delivery status',
43      'hasn\'t arrived',
44      'shipping time'
45    ]
46  })
47];
48
49// Create router
50const encoder = new OpenAIEncoder({
51  apiKey: process.env.OPENAI_API_KEY
52});
53
54const router = new Router({ routes, encoder });
55await router.initialize();
56
57// Route incoming support tickets
58async function handleSupportTicket(message: string) {
59  const result = await router.route(message);
60
61  if (result.route) {
62    console.log(`Routing to ${result.route} (confidence: ${result.score.toFixed(2)})`);
63    // Route to appropriate handler
64    return routeToHandler(result.route, message);
65  } else {
66    console.log('Unable to route - forwarding to general support');
67    return routeToGeneral(message);
68  }
69}
70
71// Example usage
72await handleSupportTicket('I was charged twice this month');
73// Routing to billing (confidence: 0.89)
🤖

2. Chatbot Intent Classification

Classify user intents in conversational AI using fast local models.

chatbot.ts
1import { Router, Route, TransformersEncoder } from 'semantic-node-router';
2
3// Define chatbot intents
4const routes = [
5  new Route({
6    name: 'book_flight',
7    utterances: [
8      'book a flight to Paris',
9      'I want to fly to London',
10      'reserve plane tickets',
11      'find me a flight'
12    ]
13  }),
14  new Route({
15    name: 'check_weather',
16    utterances: [
17      'what\'s the weather like',
18      'will it rain today',
19      'temperature forecast',
20      'is it sunny'
21    ]
22  }),
23  new Route({
24    name: 'set_reminder',
25    utterances: [
26      'remind me to call mom',
27      'set an alarm',
28      'create a reminder',
29      'don\'t let me forget'
30    ]
31  }),
32  new Route({
33    name: 'play_music',
34    utterances: [
35      'play some jazz',
36      'start my playlist',
37      'I want to listen to music',
38      'put on a song'
39    ]
40  })
41];
42
43// Use local model for fast, offline routing
44const encoder = new TransformersEncoder();
45await encoder.initialize();
46
47const router = new Router({ routes, encoder });
48await router.initialize();
49
50// Handle user input
51async function handleUserInput(message: string) {
52  const result = await router.route(message);
53
54  switch (result.route) {
55    case 'book_flight':
56      return await bookFlight(message);
57    case 'check_weather':
58      return await getWeather(message);
59    case 'set_reminder':
60      return await setReminder(message);
61    case 'play_music':
62      return await playMusic(message);
63    default:
64      return "I'm not sure how to help with that.";
65  }
66}
67
68// Example usage
69await handleUserInput('Can you play something relaxing?');
70// Routes to: play_music
📚

3. Content Categorization

Automatically categorize articles and posts by semantic similarity.

content.ts
1import { Router, Route, OpenAIEncoder } from 'semantic-node-router';
2
3// Define content categories
4const routes = [
5  new Route({
6    name: 'technology',
7    utterances: [
8      'latest smartphone releases',
9      'AI breakthrough',
10      'new software update',
11      'coding tutorial',
12      'tech startup news'
13    ]
14  }),
15  new Route({
16    name: 'sports',
17    utterances: [
18      'football match results',
19      'Olympics highlights',
20      'basketball playoffs',
21      'tennis tournament',
22      'athlete interview'
23    ]
24  }),
25  new Route({
26    name: 'business',
27    utterances: [
28      'stock market update',
29      'company earnings',
30      'merger announcement',
31      'economic forecast',
32      'startup funding'
33    ]
34  }),
35  new Route({
36    name: 'entertainment',
37    utterances: [
38      'movie review',
39      'new album release',
40      'celebrity news',
41      'TV show premiere',
42      'concert tour'
43    ]
44  })
45];
46
47const encoder = new OpenAIEncoder({
48  apiKey: process.env.OPENAI_API_KEY
49});
50
51const router = new Router({ routes, encoder });
52await router.initialize();
53
54// Categorize articles
55async function categorizeArticle(title: string, content: string) {
56  const text = `${title}. ${content.substring(0, 500)}`;
57  const result = await router.route(text);
58
59  return {
60    category: result.route || 'uncategorized',
61    confidence: result.score
62  };
63}
64
65// Example usage
66const article = {
67  title: 'Apple Announces New iPhone with AI Features',
68  content: 'Apple unveiled its latest iPhone model today...'
69};
70
71const category = await categorizeArticle(article.title, article.content);
72console.log(`Category: ${category.category} (${(category.confidence * 100).toFixed(0)}% confident)`);
73// Category: technology (94% confident)
⚙️

4. Custom Encoder

Implement your own embedding provider for specialized use cases.

custom-encoder.ts
1import { BaseEncoder, Router, Route } from 'semantic-node-router';
2
3// Implement custom encoder
4class MyCustomEncoder extends BaseEncoder {
5  name = 'my-custom-encoder';
6  scoreThreshold = 0.5;
7
8  constructor(private apiUrl: string) {
9    super();
10  }
11
12  async encode(texts: string | string[]): Promise<number[][]> {
13    const textsArray = Array.isArray(texts) ? texts : [texts];
14
15    // Call your custom embedding API
16    const response = await fetch(`${this.apiUrl}/embed`, {
17      method: 'POST',
18      headers: { 'Content-Type': 'application/json' },
19      body: JSON.stringify({ texts: textsArray })
20    });
21
22    const data = await response.json();
23    return data.embeddings;
24  }
25}
26
27// Use custom encoder
28const encoder = new MyCustomEncoder('https://my-api.com');
29
30const routes = [
31  new Route({
32    name: 'greeting',
33    utterances: ['hello', 'hi', 'hey']
34  })
35];
36
37const router = new Router({ routes, encoder });
38await router.initialize();
39
40const result = await router.route('hello there');
41console.log(result);
🔄

5. Dynamic Routes

Add and remove routes at runtime for flexible routing systems.

dynamic.ts
1import { Router, Route, OpenAIEncoder } from 'semantic-node-router';
2
3const encoder = new OpenAIEncoder({
4  apiKey: process.env.OPENAI_API_KEY
5});
6
7// Start with initial routes
8const initialRoutes = [
9  new Route({
10    name: 'billing',
11    utterances: ['payment issue', 'invoice']
12  })
13];
14
15const router = new Router({ routes: initialRoutes, encoder });
16await router.initialize();
17
18// Add new route dynamically
19await router.addRoute(
20  new Route({
21    name: 'technical',
22    utterances: ['app crashed', 'error message']
23  })
24);
25
26console.log('Route added!');
27
28// Remove route dynamically
29const removed = router.removeRoute('billing');
30console.log(`Removed: ${removed}`); // true
31
32// Get all current routes
33const currentRoutes = router.getRoutes();
34console.log(`Active routes: ${currentRoutes.map(r => r.name).join(', ')}`);
35// Active routes: technical

Ready to build your own?

Check out the full documentation to learn more about semantic routing