First, run the development server:
npm install npm run dev # or yarn dev /pnpm dev /bun dev
Open http://localhost:3000 with your browser to see the result.
- Introduction
- System Architecture
- Key Components
- User Interface
- Backend Services
- AI Integration
- Database Design
- Authentication and Security
- API Documentation
- Deployment
- Development Workflow
- Troubleshooting
- Future Enhancements
Med-friend is an advanced health assistant application designed to provide users with instant access to accurate, AI-powered health information. We combine the best publicly available health knowledge, with the best AI tools able to efficiently provide that knowledge as needed. The system combines modern web technologies with artificial intelligence to create an interactive and informative experience for users seeking health-related advice.
- AI-powered chat interface for health-related queries
- Integration with medical knowledge bases
- Responsive design for desktop and mobile use
- Frontend: Next.js (React), Material-UI
- Backend: Node.js, Firebase
- AI: OpenAI GPT models, Pinecone vector database
- Authentication: Firebase Authentication
- Database: Firebase Firestore, Pinecone
Med-friend AI follows a modern, serverless architecture leveraging cloud services for scalability and maintainability.
graph TD
User[User] -->|HTTPS| Frontend[Next.js Frontend]
subgraph Frontend
Landing[Landing Page]
Chat[Chat Interface]
end
Frontend -->|API Calls| Routes[API Routes]
subgraph Routes
ChatProcess[Chat Processing]
UserAuth[User Auth]
VectorSearch[Vector Search]
end
ChatProcess -->|NLP Requests| LLMAPI[LLM API]
UserAuth -->|Authenticate| FireAuth[Firebase Auth]
VectorSearch -->|Query| PineconeAPI[Pinecone API]
FireAuth --> Firestore[Firebase Firestore]
PineconeAPI --> Firestore
classDef frontend fill:#d0e0ff,stroke:#333,stroke-width:2px;
classDef backend fill:#ffe0d0,stroke:#333,stroke-width:2px;
classDef external fill:#d0ffe0,stroke:#333,stroke-width:2px;
class Frontend frontend;
class Routes backend;
class LLMAPI,FireAuth,PineconeAPI,Firestore external;
- Next.js Frontend: Serves the user interface and handles client-side logic.
- API Routes: Serverless functions handling backend logic and external service integration.
- Multiple LLM Provider API's: Provide natural language processing capabilities.
- Firebase Auth: Manages user authentication.
- Firebase Firestore: Stores user data and chat history.
- Pinecone Vector DB: Stores and retrieves medical information for context-aware AI responses.
The main entry point of the application, introducing users to Med-friend AI.
Key features:
- Responsive design with Material-UI
- Introduction to Med-friend AI capabilities
- Options to try the HealthBot or enter the full chat interface
The main chat interface for logged-in users.
Key features:
- Chat history sidebar
- Real-time chat interface
- New chat creation
- User authentication status management
Handles user authentication processes.
Key features:
- Login and signup functionality
- Email/password and Google authentication options
- Integration with Firebase Authentication
A floating chat widget for quick interactions with the AI assistant.
Key features:
- Minimizable chat interface
- Real-time AI responses
- Typing indicators for better user experience
Handles chat requests and integrates with OpenAI and Pinecone.
Key features:
- OpenAI GPT model integration
- Pinecone vector search for relevant medical information
- Context-aware response generation
Sets up Firebase services for the application.
Key features:
- Firebase app initialization
- Authentication service setup
- Firestore database initialization
The user interface is built using React components and styled with Material-UI, ensuring a responsive and accessible design across devices.
The landing page (src/app/page.js) serves as the main entry point for users. It features:
- A hero section with a call-to-action
- Feature highlights of Med-friend AI
- Options to try the HealthBot or access the full chat interface
- Login/Signup buttons
FeatureCard: Displays individual features of the applicationAppBar: Navigation bar with authentication optionsModal: For displaying the authentication form
The chat interface (src/app/chat/page.js) is the core of the application, where users interact with the AI assistant. It includes:
- A sidebar with chat history
- The main chat area with message bubbles
- An input area for user messages
- A disclaimer about the nature of AI-provided information
ChatListContainer: Displays the list of previous chatsChatListItem: Individual chat session in the sidebarMainContent: Contains the chat messages and input areaDisclaimerBox: Informs users about the limitations of AI advice
The popup chat (src/app/components/PopupChat.js) provides a floating chat interface for quick interactions. Features include:
- Minimizable chat window
- Real-time message display
- Typing indicators
StyledPaper: The main container for the popup chatChatHeader: Contains the title and close buttonMessageBubble: Displays individual messagesTypingIndicator: Shows when the AI is generating a response
The application uses a combination of Material-UI's built-in styling system and custom styles:
- Theme customization in
src/app/page.js - Global styles in
src/app/globals.css - Component-specific styles using the
styledfunction from Material-UI
The backend of Med-friend AI is primarily serverless, utilizing Next.js API routes and cloud services.
Located in src/app/api/chat/route.js, the main API route handles chat functionality:
- Receives user messages
- Queries Pinecone for relevant medical information
- Sends context and user message to OpenAI
- Returns AI-generated response to the frontend
Firebase provides authentication and database services:
- Authentication: Handles user signup, login, and session management
- Firestore: Stores user data and chat history
Configuration and initialization of Firebase services are done in src/app/utils/firebase.js.
Pinecone is used to store and retrieve medical information efficiently:
- Stores embeddings of medical information
- Provides fast similarity search for relevant context
The Pinecone service is initialized and queried in the chat API route.
Med-friend AI leverages OpenAI's GPT models for generating intelligent responses to user queries.
The application uses the OpenAI API to generate responses:
- Model: GPT-4 (or GPT-3.5-turbo, depending on configuration)
- Input: User message and relevant medical context
- Output: AI-generated response
The integration is handled in the chat API route (src/app/api/chat/route.js).
To provide more accurate and relevant responses, the system:
- Queries Pinecone with the user's message
- Retrieves relevant medical information
- Includes this information as context when querying OpenAI
This process enhances the AI's ability to provide informed and contextually appropriate responses.
Med-friend AI uses two database systems: Firebase Firestore and Pinecone Vector Database.
Firestore is used to store user data and chat history. The data model is as follows: users/ {userId}/ conversations/ {conversationId}/ messages/ {messageId}/ content: string createdAt: timestamp userId: string This structure allows for efficient retrieval of user-specific chat histories.
Pinecone stores medical information as vector embeddings, allowing for fast similarity search:
- Each entry contains:
- Vector embedding of medical text
- Metadata including the original text and any relevant tags
The Pinecone database is queried in the chat API route to retrieve context for AI responses.
Med-friend AI implements robust authentication and security measures to protect user data and ensure secure interactions.
Firebase Authentication is used to handle user signup and login processes:
- Email/password authentication
- Google Sign-In integration
The Auth component (src/app/components/Auth.js) manages the UI for these processes.
- Environment Variables: Sensitive information like API keys are stored in environment variables (
.env.local) - Server-side API Calls: OpenAI API calls are made server-side to protect API keys
- HTTPS: All communications are encrypted using HTTPS
- Firebase Security Rules: Firestore database access is controlled by Firebase security rules
- User chat histories are stored securely in Firebase Firestore
- No personal health information is permanently stored
- Users are advised not to share sensitive personal information in chats
Endpoint: /api/chat
Method: POST
Request Body: json { "messages": [ { "role": "user", "content": "User's message here" } ], "chatId": "optional-chat-id" }
- 400 Bad Request: Missing required parameters
- 500 Internal Server Error: Server-side processing error
Firebase Authentication is used, which provides RESTful endpoints for authentication operations. Refer to the Firebase Authentication REST API documentation for detailed information on these endpoints.
Med-friend AI is designed to be deployed on cloud platforms that support Next.js applications.
- Set up environment variables on the deployment platform
- Build the Next.js application:
npm run build - Deploy the built application to the chosen platform (e.g., Vercel, Netlify)
- Configure custom domain and SSL certificate if required
Ensure the following environment variables are set:
NEXT_PUBLIC_FIREBASE_*: Firebase configuration variablesOPENAI_API_KEY: OpenAI API keyPINECONE_API_KEY: Pinecone API keyPINECONE_ENVIRONMENT: Pinecone environmentPINECONE_INDEX_NAME: Pinecone index name
Set up a CI/CD pipeline to automate the deployment process:
- Configure GitHub Actions or similar CI/CD tool
- Set up automated testing before deployment
- Configure automatic deployment to staging environment on pull requests
- Set up manual approval for production deployments
- Clone the repository
- Install dependencies:
npm install - Set up local environment variables in
.env.local - Run the development server:
npm run dev
- ESLint is used for code linting
- Prettier is used for code formatting
- Run linter:
npm run lint
- Jest is used for unit and integration testing
- React Testing Library for component testing
- Run tests:
npm test
- Git is used for version control
- Follow conventional commit messages
- Create feature branches for new features or bug fixes
- Use pull requests for code reviews
- Keep README and this documentation up to date
- Use JSDoc comments for function and component documentation
- Generate API documentation using tools like Swagger or Postman
- API Key Issues: Ensure all API keys are correctly set in environment variables
- Firebase Configuration: Verify Firebase configuration in
firebase.js - Pinecone Connection: Check Pinecone API key and environment settings
- OpenAI API Errors: Verify OpenAI API key and usage limits
- Use browser developer tools for frontend debugging
- Check server logs for backend issues
- Enable verbose logging in development environment
- Use logging service like Sentry for production error tracking
- Implement application performance monitoring (APM) tools
- Monitor server response times and error rates
- Track AI response generation times
Potential areas for future development include:
-
Implement more sophisticated conversation management
- Context retention across multiple messages
- User preference learning
-
Add support for file uploads (e.g., medical reports)
- Image analysis for visual symptoms
- PDF parsing for medical documents
-
Enhance error handling and user feedback mechanisms
- Implement error boundaries in React components
- Provide more detailed error messages to users
-
Implement a user feedback and response rating system
- Allow users to rate AI responses
- Use feedback to improve AI training
-
Develop an admin panel for monitoring conversations and fine-tuning the AI
- Dashboard for usage statistics
- Tools for analyzing common queries and improving responses
-
Integrate with additional medical databases for more comprehensive information
- Connect with public health databases
- Integrate with electronic health record (EHR) systems
-
Implement multi-language support
- Localization of UI elements
- Multi-language AI response generation
-
Add voice input/output capabilities
- Speech-to-text for user input
- Text-to-speech for AI responses
-
Implement advanced analytics
- User behavior analysis
- Health trend identification
-
Enhance mobile experience
- Develop native mobile apps
- Optimize performance for low-bandwidth connections
By continuously improving and expanding the capabilities of Med-friend AI, we aim to provide an increasingly valuable tool for users seeking health information and advice.
This is a Next.js project bootstrapped with create-next-app.
To learn more about Next.js, take a look at the following resources:
- Next.js Documentation - learn about Next.js features and API.
- Learn Next.js - an interactive Next.js tutorial.
You can check out the Next.js GitHub repository - your feedback and contributions are welcome!
The easiest way to deploy your Next.js app is to use the Vercel Platform from the creators of Next.js.
Check out our Next.js deployment documentation for more details.