This is the backend server for the Chat-OIO application. It uses Express, Socket.IO, and the OpenAI API to provide a real-time chat service with an AI assistant.
- Real-time communication with Socket.IO
- AI-powered chat using the OpenAI API
- Express server for handling HTTP requests
- CORS support for cross-origin requests
- Node.js and npm installed on your machine
- An OpenAI API key
- Clone the repository:
git clone https://github.com/your-username/chat-express-oio-openai.git
- Navigate to the
chat-oio-serverdirectory:cd chat-express-oio-openai/chat-oio-server - Install the dependencies:
npm install
- Create a
.envfile in the root of thechat-oio-serverdirectory and add your OpenAI API key and the base URL for the AI:OPEN_AI_API_KEY=your-openai-api-key GITHUB_AI_BASE_URL=your-ai-base-url
To start the server, run the following command:
npm run serverThe server will start on port 8000 by default.
chat-oio-server/
├── config/
│ └── openai.config.js # OpenAI client configuration
├── socket/
│ ├── handlers.js # Socket event handlers
│ └── socketServer.js # Socket.IO server setup
├── .env # Environment variables
├── .gitignore # Git ignore file
├── index.js # Express server entry point
├── package.json # Project dependencies and scripts
└── package-lock.json
express: Web framework for Node.jssocket.io: Real-time communication libraryopenai: OpenAI API clientcors: Middleware for enabling CORSdotenv: Module for loading environment variablesnodemon: Utility for auto-restarting the server during development
- The Express server is initialized in
index.js. - The Socket.IO server is registered in
socket/socketServer.jsand attached to the Express server. - When a client connects, the
connectionevent is fired insocket/socketServer.js. - The server listens for
user-messageevents from the client. - When a
user-messageis received, themessageHandlerinsocket/handlers.jsis called. - The
messageHandlersends the message to the OpenAI API to get an AI response. - The AI response is streamed back to the client via the
ai-responseevent. - If there is an error, the
ai-errorevent is emitted.