A Node.js chatbot MVP built with Express and OpenAI, featuring streaming responses and conversation memory. This is a Node.js port of the original Python Streamlit version.
- π€ AI Chatbot: Powered by OpenAI's GPT-3.5-turbo
- π¬ Streaming Responses: Real-time message streaming for better UX
- π§ Conversation Memory: Maintains context throughout the conversation
- π Web Interface: Clean, responsive chat interface
- π Session Management: Clear conversation history
- π± Mobile Responsive: Works on desktop and mobile devices
- Node.js (v14 or higher)
- npm or yarn
- OpenAI API key
-
Clone or navigate to the project directory
cd nodejs-chatbot -
Install Dependencies
npm install
-
Set up Environment Variables
- Copy
env.exampleto.env - Add your OpenAI API key:
OPENAI_API_KEY=your_actual_api_key_here
- Copy
-
Run the Application
For development (with auto-restart):
npm run dev
For production:
npm start
-
Open in Browser
- The app will be available at
http://localhost:3000 - The server will display the exact URL in the console
- The app will be available at
- Start Chatting: Type your message in the chat input at the bottom
- View Responses: Watch as the AI response streams in real-time
- Clear Memory: Use the "Clear Conversation" button in the sidebar to reset
- View Memory: Check the sidebar to see how many messages are stored
- Status Indicator: Monitor connection status in the sidebar
nodejs-chatbot/
βββ server.js # Express server and API endpoints
βββ Chatbot.js # LongChainChatbot class implementation
βββ package.json # Node.js dependencies and scripts
βββ env.example # Environment variables template
βββ README.md # This file
βββ public/ # Frontend files
βββ index.html # Main HTML page
βββ styles.css # CSS styling
βββ script.js # Frontend JavaScript
POST /api/chat/stream- Stream chat responsesPOST /api/chat- Regular chat responses (non-streaming)
POST /api/session- Create new chat sessionPOST /api/clear- Clear conversation memoryGET /api/memory/:sessionId- Get conversation memory info
GET /api/health- Server health checkGET /- Serve the main chat interface
- Initialization: Sets up OpenAI client and conversation memory
- getResponse(): Standard response generation
- getStreamingResponse(): Streaming response for real-time chat
- clearMemory(): Reset conversation history
- getMemory(): Get conversation history
- getMemoryLength(): Get number of messages in memory
- Session Management: UUID-based session handling
- Streaming Support: Server-sent events for real-time responses
- CORS Support: Cross-origin resource sharing
- Error Handling: Comprehensive error handling and logging
- Static File Serving: Serves frontend files
- Responsive Design: Mobile-friendly interface
- Real-time Streaming: Live message updates
- Session Persistence: Maintains chat state
- Status Monitoring: Connection and API key status
Edit the OpenAI model settings in Chatbot.js:
const completion = await this.openai.chat.completions.create({
model: 'gpt-4', // Change model
temperature: 0.5, // Adjust creativity
max_tokens: 2000, // Adjust response length
// ... other options
});Modify server settings in server.js:
const PORT = process.env.PORT || 3000; // Change default portCustomize the appearance in public/styles.css:
- Color scheme
- Layout dimensions
- Typography
- Responsive breakpoints
| Variable | Description | Required | Default |
|---|---|---|---|
OPENAI_API_KEY |
Your OpenAI API key | Yes | - |
PORT |
Server port | No | 3000 |
-
API Key Error
- Ensure
.envfile exists with validOPENAI_API_KEY - Check that the key has sufficient credits
- Verify the key is not expired
- Ensure
-
Installation Errors
- Run
npm installto ensure all dependencies are installed - Check Node.js version:
node --version(should be v14+) - Clear npm cache:
npm cache clean --force
- Run
-
Server Issues
- Check if port 3000 is available:
netstat -an | findstr :3000 - Try a different port:
PORT=3001 npm start - Check server logs for detailed error messages
- Check if port 3000 is available:
-
Streaming Issues
- Ensure your browser supports Server-Sent Events
- Check network connectivity
- Verify CORS settings if accessing from different domain
Enable debug logging by setting:
DEBUG=* npm start- Backend Changes: Modify
server.jsorChatbot.js - Frontend Changes: Update files in
public/directory - Dependencies: Add new packages to
package.json
Test the API endpoints using curl:
# Health check
curl http://localhost:3000/api/health
# Create session
curl -X POST http://localhost:3000/api/session
# Send message (replace SESSION_ID)
curl -X POST http://localhost:3000/api/chat \
-H "Content-Type: application/json" \
-d '{"message": "Hello!", "sessionId": "SESSION_ID"}'- Memory Management: Sessions are stored in memory (not persistent)
- Rate Limiting: Consider implementing rate limiting for production
- Caching: Add Redis for session persistence in production
- Load Balancing: Use multiple server instances for high traffic
- API Key Protection: Never commit
.envfiles to version control - Input Validation: Sanitize user inputs
- Rate Limiting: Implement request rate limiting
- HTTPS: Use HTTPS in production
- CORS: Configure CORS properly for production
This MVP provides a solid foundation. Consider adding:
- Vector Database: For document-based Q&A
- Custom Prompts: System prompts for specific use cases
- File Upload: Process documents and PDFs
- User Authentication: Multi-user support
- Database Integration: Persistent conversation storage
- WebSocket Support: Real-time bidirectional communication
- Rate Limiting: API request throttling
- Logging: Comprehensive logging and monitoring
- Docker Support: Containerization for easy deployment
| Feature | Python (Streamlit) | Node.js (Express) |
|---|---|---|
| Framework | Streamlit | Express.js |
| Frontend | Built-in Streamlit UI | Custom HTML/CSS/JS |
| Streaming | Streamlit streaming | Server-Sent Events |
| Session Management | Streamlit session state | UUID-based sessions |
| Deployment | Streamlit Cloud | Any Node.js hosting |
| Customization | Limited by Streamlit | Full control |
| Performance | Good for prototyping | Better for production |
MIT License - feel free to use and modify as needed.
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
For issues and questions:
- Check the troubleshooting section
- Review server logs
- Test API endpoints directly
- Check OpenAI API status