Orchestrates multiple chatbots into seamless, multi agent conversations Node.js
👤 Sharing: AI
```javascript
// orchestrator.js
// This Node.js program orchestrates multiple chatbots in a multi-agent conversation.
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
// Mock Chatbot Implementations (Replace with actual chatbot integrations)
class ChatbotA {
constructor(name) {
this.name = name;
}
async handleInput(input) {
// Simulate chatbot A's response logic (e.g., sentiment analysis, simple question answering)
if (input.includes('hello')) {
return `${this.name}: Greetings! How can I assist you today?`;
} else if (input.includes('weather')) {
return `${this.name}: Checking the weather... (pretends to call a weather API)`;
} else {
return `${this.name}: I'm not quite sure I understand. Could you rephrase?`;
}
}
}
class ChatbotB {
constructor(name) {
this.name = name;
}
async handleInput(input) {
// Simulate chatbot B's response logic (e.g., booking appointments, providing information)
if (input.includes('appointment')) {
return `${this.name}: Let's schedule an appointment. What date and time works for you?`;
} else if (input.includes('information')) {
return `${this.name}: What kind of information are you looking for?`;
} else {
return `${this.name}: Hmm, I don't have specific information on that.`;
}
}
}
// Orchestrator Class
class Orchestrator {
constructor() {
this.chatbots = {
chatbotA: new ChatbotA('WeatherBot'),
chatbotB: new ChatbotB('AppointmentBot'),
};
this.activeChatbot = 'chatbotA'; // Start with chatbot A
}
async routeMessage(input) {
// Simple routing logic: Based on keywords, decide which chatbot handles the input.
if (input.includes('weather')) {
this.activeChatbot = 'chatbotA';
} else if (input.includes('appointment') || input.includes('schedule')) {
this.activeChatbot = 'chatbotB';
}
else if (input.includes("Switch back")){
this.activeChatbot = 'chatbotA'
}
// Pass the input to the appropriate chatbot
const response = await this.chatbots[this.activeChatbot].handleInput(input);
return response;
}
async startConversation() {
console.log('Welcome to the Multi-Agent Chat!');
console.log('You are currently interacting with ' + this.chatbots[this.activeChatbot].name);
const askQuestion = () => {
readline.question('You: ', async (input) => {
const response = await this.routeMessage(input);
console.log(response);
askQuestion(); // Continue the conversation
});
};
askQuestion(); // Start the conversation loop
}
}
// Main program execution
const orchestrator = new Orchestrator();
orchestrator.startConversation();
// Example Usage:
//
// 1. Run the program: node orchestrator.js
// 2. Type messages and see how the orchestrator routes them to different chatbots.
//
// Try these inputs:
// - hello
// - what's the weather like today?
// - I want to schedule an appointment.
// - what is the meaning of life? (will be handled by the default)
// - Can you provide some information?
// - Switch back
// - Hello again
```
Key improvements and explanations:
* **Clearer Structure:** The code is organized into classes (ChatbotA, ChatbotB, and Orchestrator) for better modularity and readability.
* **Mock Chatbot Implementations:** `ChatbotA` and `ChatbotB` are mock implementations. The `handleInput` methods simulate the logic of a real chatbot (e.g., sentiment analysis, API calls, data lookup). You would replace these with actual chatbot SDKs or API integrations.
* **Orchestrator Class:** The `Orchestrator` class manages the chatbots and routes messages between them.
* **`routeMessage` Function:** This is the core of the orchestrator. It decides which chatbot should handle the incoming message based on keywords (or other more sophisticated criteria). Crucially, it *returns* the response from the selected chatbot.
* **`activeChatbot` State:** The orchestrator keeps track of which chatbot is currently active. This allows for conversational context.
* **`startConversation` Function:** This function sets up the conversation loop using `readline` to get input from the user and print responses. It calls `askQuestion` recursively to keep the conversation going.
* **`readline` for Input:** Uses the `readline` module for getting user input from the console, making it interactive.
* **`async/await`:** Uses `async/await` to handle asynchronous operations (like waiting for a chatbot to respond). This avoids callback hell and makes the code cleaner.
* **Error Handling (Basic):** In a real application, you would need to add more robust error handling (e.g., try/catch blocks, logging).
* **Example Usage:** Provides clear instructions on how to run the program and test it.
* **Comments:** Includes comprehensive comments to explain each part of the code.
* **Extensible:** Easy to add more chatbots by simply creating new classes and adding them to the `chatbots` object in the `Orchestrator`. You would also need to update the `routeMessage` function to handle the new chatbots.
* **No external dependencies:** This version uses only built-in Node.js modules, making it easy to run.
* **State management:** Demonstrates simple state management (activeChatbot), but more complex state could be managed with a proper state management library.
How to run the code:
1. **Save:** Save the code as `orchestrator.js`.
2. **Open Terminal:** Open a terminal or command prompt.
3. **Navigate:** Navigate to the directory where you saved the file.
4. **Run:** Execute the command `node orchestrator.js`.
5. **Interact:** Start typing messages and see how the orchestrator routes them to different chatbots.
To use actual chatbots, you would replace the mock `handleInput` methods with calls to the chatbot's API or SDK. For example, you might use the Dialogflow API, the Microsoft Bot Framework SDK, or a custom chatbot API. You would also need to handle authentication and authorization for the chatbots. The `routeMessage` function could be extended to use more sophisticated criteria for routing messages, such as natural language understanding (NLU) or machine learning (ML) models.
👁️ Viewed: 5
Comments