REST API for an intelligent assistant with conversational capabilities using OpenAI, Google Calendar integration, and user management with Firebase Authentication.
This project is a backend API built with Node.js, TypeScript, and Express that provides an intelligent virtual assistant capable of:
- Maintaining contextual conversations using OpenAI Assistants API
- Automatically scheduling meetings in Google Calendar
- Storing client/user information
- Managing files to enrich the assistant's context
- Authenticating users via Firebase
- Contextual Conversations: Maintains conversation history in threads
- Function Calling: Ability to execute specific functions:
storeUserData: Stores user data (name, email, phone)scheduleMeeting: Schedules meetings in Google Calendar with Google Meet
- File Management: Supports file uploads to enrich the assistant's knowledge
- Token Tracking: Monitors OpenAI token usage per user
- Automatic meeting scheduling
- Google Meet link generation
- Support for multiple attendees
- Per-user timezone management
- Authentication via Firebase Authentication
- Authorization middleware on protected routes
- Helmet for HTTP security
- Configured CORS
- Support for multiple file types
- Secure temporary storage
- AWS S3 integration
- Batch processing
- Node.js - Runtime environment
- TypeScript - Typed language
- Express - Web framework
- MongoDB + Mongoose - NoSQL database
- OpenAI API - Intelligent assistant and natural language processing
- Google Calendar API - Event and meeting management
- Firebase Admin - Authentication and authorization
- AWS S3 - File storage
- Winston - Logging system
- Helmet - HTTP security
- Express Validator - Data validation
- Axios - HTTP client
- Moment Timezone - Timezone management
chatbot/
βββ config/ # Application configuration
β βββ default.js # Default configuration
β βββ production.js # Production configuration
β βββ test.js # Test configuration
β βββ custom-environment-variables.js
βββ src/
β βββ index.ts # Entry point
β βββ app/
β β βββ index.ts # Express configuration
β β βββ config/
β β βββ winston.config.ts # Logging configuration
β βββ middlewares/
β β βββ auth.ts # Firebase authentication
β β βββ response.ts # Response formatting
β β βββ fileUploadMiddleware.ts # File handling
β βββ modules/
β β βββ db.module.ts # MongoDB connection
β β βββ assistant/ # Assistant module
β β β βββ assistant.model.ts
β β β βββ assistant.service.ts
β β β βββ assistant.interface.ts
β β β βββ assistant.validation.ts
β β βββ user/ # User module
β β β βββ user.model.ts
β β β βββ user.service.ts
β β β βββ user.interface.ts
β β β βββ user.validation.ts
β β βββ functionCalling/ # OpenAI function calling
β β β βββ functionCalling.service.ts
β β β βββ functionCalling.interfaces.ts
β β βββ common/ # Common services
β β β βββ openai/
β β β β βββ openAI.ts
β β β β βββ axiosOpenAI.ts
β β β β βββ functionCalling/
β β β β βββ functions.ts
β β β β βββ toolsDefinition.ts
β β β βββ google/
β β β β βββ googleAuth.service.ts
β β β β βββ googleCalendar.service.ts
β β β β βββ googleCalendarFileBuilder.ts
β β β βββ plugins/
β β β βββ firebase.ts
β β β βββ catchAsync.ts
β β β βββ icsFileManager.ts
β β βββ errors/ # Error handling
β β βββ ApiError.ts
β β βββ index.ts
β βββ routes/
β βββ routes.ts # Route configuration
β βββ apiv1/
β βββ api.routes.ts
β βββ assistant/ # Assistant routes
β βββ users/ # User routes
β βββ functionCalling/ # Function routes
β βββ google/ # Google Calendar routes
βββ .env.example # Environment variables example
βββ package.json
βββ tsconfig.json
- Node.js >= 14.x
- MongoDB >= 4.x
- OpenAI account with API access
- Configured Firebase project
- Google Cloud account with Calendar API enabled
- AWS account (optional, for file storage)
- Clone the repository
git clone git@github.com:jcmn182/chatbot.git
cd chatbot- Install dependencies
npm install- Configure environment variables
Copy the .env.example file to .env and configure the variables:
cp .env.example .envEdit .env with your credentials:
# Server
PORT=3000
ENVIRONMENT=development
# Database
MONGODB_URI=mongodb://localhost:27017/assistant-db
# Basic authentication (optional)
AUTH_API_USERNAME=admin
AUTH_API_PASSWORD=secret
# Firebase
FIRE_BASE_TYPE=service_account
FIRE_BASE_PROJECT_ID=your-project-id
FIRE_BASE_PRIVATE_KEY_ID=your-private-key-id
FIRE_BASE_PRIVATE_KEY=-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n
FIRE_BASE_CLIENT_EMAIL=firebase-adminsdk@your-project.iam.gserviceaccount.com
FIRE_BASE_CLIENT_ID=your-client-id
FIRE_BASE_AUTH_URI=https://accounts.google.com/o/oauth2/auth
FIRE_BASE_TOKEN_URI=https://oauth2.googleapis.com/token
FIRE_BASE_AUTH_PROVIDER_X509_CERT_URL=https://www.googleapis.com/oauth2/v1/certs
FIRE_BASE_CLIENT_X509_CERT_URL=your-cert-url
FIRE_BASE_UNIVERSE_DOMAIN=googleapis.com
# OpenAI
OPENAI_TOKEN=sk-...your-openai-api-key
# Google OAuth (for Calendar API)
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret- Build the project
npm run build- Start the server
Development mode (with hot reload):
npm run start:devProduction mode:
npm startThe server will start on the configured port (default: 3000).
http://localhost:3000/api/v1
Most endpoints require Firebase Authentication. Include the Firebase ID token in the Authorization header:
Authorization: Bearer <firebase-id-token>
Create User
POST /api/v1/user
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"timeZone": "America/New_York"
}Get User
GET /api/v1/user/:userId
Authorization: Bearer <token>Update User
PATCH /api/v1/user/:userId
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "John Smith",
"timeZone": "America/Los_Angeles"
}Create Assistant
POST /api/v1/assistant
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "My Personal Assistant"
}Chat with Assistant
POST /api/v1/assistant/chat
Authorization: Bearer <token>
Content-Type: application/json
{
"message": "Schedule a meeting for tomorrow at 2pm",
"threadId": "thread_abc123" // Optional, for continuing a conversation
}Upload File to Assistant
POST /api/v1/assistant/upload
Authorization: Bearer <token>
Content-Type: multipart/form-data
file: <your-file>Supported file types:
- PDF (.pdf)
- Word documents (.docx)
- Text files (.txt)
- Code files (.py, .js, .ts, etc.)
Connect Google Calendar
POST /api/v1/calendar/connect
Authorization: Bearer <token>
Content-Type: application/json
{
"accessToken": "ya29...",
"refreshToken": "1//...",
"redirectUri": "http://localhost:3000/callback"
}Schedule Meeting
POST /api/v1/calendar/schedule
Authorization: Bearer <token>
Content-Type: application/json
{
"summary": "Project Review Meeting",
"description": "Review Q1 project progress",
"start": "2025-01-15T14:00:00-05:00",
"end": "2025-01-15T15:00:00-05:00",
"attendees": ["colleague@example.com"]
}Store User Data
POST /api/v1/functions/store-user-data
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "Jane Doe",
"email": "jane@example.com",
"number": "+1234567890"
}All endpoints return responses in the following format:
Success Response:
{
"response": {
// Response data
}
}Error Response:
{
"code": 400,
"message": "Error description",
"stack": "..." // Only in development mode
}Edit config/default.js to configure MongoDB connection:
mongodb: {
uri: process.env.MONGODB_URI
}The assistant uses OpenAI's Assistants API. Configure your API key in the environment variables.
To enable Google Calendar integration:
- Create a project in Google Cloud Console
- Enable Calendar API
- Create OAuth 2.0 credentials
- Configure redirect URIs
- Add credentials to environment variables
- Create a Firebase project
- Generate a service account key
- Add all Firebase configuration to environment variables
Run linting:
npm run lintFix linting issues:
npm run lint:fixThe API maintains conversation context using OpenAI threads:
- Each conversation has a unique
threadId - Messages are stored in threads for context
- Threads are associated with users
- Token usage is tracked per user
- User sends message to assistant
- Assistant determines if a function should be called
- Function is executed (e.g., scheduling meeting)
- Result is returned to assistant
- Assistant formulates response with action confirmation
- User authorizes Google Calendar access
- Refresh token is stored securely
- When scheduling is needed, access token is obtained
- Meeting is created with Google Meet link
- ICS file can be generated for email invitations
- All sensitive routes are protected with Firebase authentication
- Environment variables are used for all credentials
- Helmet middleware provides HTTP security headers
- CORS is configured to control cross-origin requests
- File uploads are stored in temporary directories with size limits
- MongoDB connection uses secure URI with authentication
Ensure all production environment variables are set:
- Use strong authentication credentials
- Configure production MongoDB URI
- Use production Firebase credentials
- Set
ENVIRONMENT=production
npm run build
npm start- Heroku: Easy deployment with add-ons for MongoDB
- AWS EC2/ECS: Full control and scalability
- Google Cloud Run: Serverless container deployment
- DigitalOcean: Simple VPS deployment
This project uses:
- ESLint for code linting (Airbnb style guide)
- Prettier for code formatting
- TypeScript for type