8000 GitHub - kunal-nt/vectorMongo Β· GitHub
[go: up one dir, main page]

Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

5 Commits

Folders and files

Repository files navigation

LongChain Chatbot MVP - Node.js Version

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.

Features

  • πŸ€– 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

Setup

Prerequisites

  • Node.js (v14 or higher)
  • npm or yarn
  • OpenAI API key

Installation

  1. Clone or navigate to the project directory

    cd nodejs-chatbot
  2. Install Dependencies

    npm install
  3. Set up Environment Variables

    • Copy env.example to .env
    • Add your OpenAI API key:
      OPENAI_API_KEY=your_actual_api_key_here
      
  4. Run the Application

    For development (with auto-restart):

    npm run dev

    For production:

    npm start
  5. Open in Browser

    • The app will be available at http://localhost:3000
    • The server will display the exact URL in the console

Usage

  1. Start Chatting: Type your message in the chat input at the bottom
  2. View Responses: Watch as the AI response streams in real-time
  3. Clear Memory: Use the "Clear Conversation" button in the sidebar to reset
  4. View Memory: Check the sidebar to see how many messages are stored
  5. Status Indicator: Monitor connection status in the sidebar

Project Structure

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

API Endpoints

Chat Endpoints

  • POST /api/chat/stream - Stream chat responses
  • POST /api/chat - Regular chat responses (non-streaming)

Session Management

  • POST /api/session - Create new chat session
  • POST /api/clear - Clear conversation memory
  • GET /api/memory/:sessionId - Get conversation memory info

Utility

  • GET /api/health - Server health check
  • GET / - Serve the main chat interface

Key Components

LongChainChatbot Class (Chatbot.js)

  • 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

Express Server (server.js)

  • 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

Frontend (public/)

  • Responsive Design: Mobile-friendly interface
  • Real-time Streaming: Live message updates
  • Session Persistence: Maintains chat state
  • Status Monitoring: Connection and API key status

Customization

Model Configuration

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
});

Server Configuration

Modify server settings in server.js:

const PORT = process.env.PORT || 3000; // Change default port

Frontend Styling

Customize the appearance in public/styles.css:

  • Color scheme
  • Layout dimensions
  • Typography
  • Responsive breakpoints

Environment Variables

Variable Description Required Default
OPENAI_API_KEY Your OpenAI API key Yes -
PORT Server port No 3000

Troubleshooting

Common Issues

  1. API Key Error

    • Ensure .env file exists with valid OPENAI_API_KEY
    • Check that the key has sufficient credits
    • Verify the key is not expired
  2. Installation Errors

    • Run npm install to ensure all dependencies are installed
    • Check Node.js version: node --version (should be v14+)
    • Clear npm cache: npm cache clean --force
  3. 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
  4. Streaming Issues

    • Ensure your browser supports Server-Sent Events
    • Check network connectivity
    • Verify CORS settings if accessing from different domain

Debug Mode

Enable debug logging by setting:

DEBUG=* npm start

Development

Adding New Features

  1. Backend Changes: Modify server.js or Chatbot.js
  2. Frontend Changes: Update files in public/ directory
  3. Dependencies: Add new packages to package.json

Testing

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"}'

Performance Considerations

  • 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

Security Considerations

  • API Key Protection: Never commit .env files 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

Next Steps

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

Comparison with Python Version

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

License

MIT License - feel free to use and modify as needed.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Test thoroughly
  5. Submit a pull request

Support

For issues and questions:

  1. Check the troubleshooting section
  2. Review server logs
  3. Test API endpoints directly
  4. Check OpenAI API status

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0