📘 Issue Description
Integrate OpenAI (or similar AI service) for real-time conversation practice functionality. This feature will allow authenticated users to engage in AI-powered conversations to practice their language skills. The implementation should include a secure /chat/ai POST endpoint that handles chat requests and responses while maintaining user authentication and proper error handling.
🔍 Steps
Backend Implementation
-
Install OpenAI SDK
- Add
openai package to dependencies
- Add OpenAI API key configuration to environment variables and settings
-
Create Chat Controller
- Create
src/controllers/chat.controller.ts
- Implement
sendMessage method for handling chat requests
- Handle OpenAI API integration with proper error handling
- Support conversation context/history management
-
Create Chat Service
- Create
src/services/chat.service.ts
- Implement OpenAI API calls with proper configuration
- Handle rate limiting and token management
- Support different conversation modes (practice levels: A1, A2, B1, B2, C1, C2)
-
Create Chat Routes
- Create
src/routes/api/modules/chat.routes.ts
- Implement
POST /api/v1/chat/ai endpoint
- Apply authentication middleware (
isAuthorized())
- Add request validation middleware
-
Create Validation Schema
- Create
src/models/validations/chat.validators.ts
- Validate message content, conversation context, and practice level
- Ensure proper sanitization of user input
-
Environment Configuration
- Add
OPENAI_API_KEY to environment variables
- Add
OPENAI_MODEL configuration (default: gpt-3.5-turbo)
- Update settings schema in
src/core/config/settings.ts
-
Error Handling & Security
- Implement proper error responses for API failures
- Add rate limiting specific to chat endpoints
- Sanitize user input and AI responses
- Handle OpenAI API quota limits gracefully
Database Considerations (Optional Enhancement)
- Chat History Storage
- Consider adding chat history tables to Prisma schema
- Store conversation sessions for user progress tracking
- Implement data retention policies
✅ Acceptance Criteria
API Specification
Endpoint: POST /api/v1/chat/ai
Headers:
Request Body:
{
"message": "Hello, I want to practice English conversation",
"conversationContext": [],
"practiceLevel": "B1",
"conversationType": "general"
}
Success Response (200):
{
"success": true,
"message": "Chat response generated successfully",
"data": {
"response": "Hello! I'd be happy to help you practice English...",
"conversationId": "uuid-string",
"timestamp": "2024-01-15T10:30:00Z"
}
}
🌎 References
- OpenAI API Documentation
- OpenAI Node.js SDK
- Existing codebase patterns in
/src/controllers/ and /src/services/
- Authentication patterns in
/src/middlewares/authentication.ts
- Validation patterns in
/src/models/validations/
📜 Additional Notes
Technical Considerations
- Cost Management: Implement token counting and usage tracking to manage OpenAI API costs
- Performance: Consider implementing response caching for common practice scenarios
- Scalability: Design with future multi-language support in mind
- Privacy: Ensure user messages are handled according to privacy policies
- Fallback: Consider fallback responses if OpenAI API is unavailable
Integration Points
- Follow existing controller patterns (
auth.controller.ts, question.controller.ts)
- Use existing authentication middleware (
isAuthorized())
- Follow validation patterns from
question.validators.ts
- Maintain consistency with existing API response formats
- Use existing logging configuration from
core/config/logger.ts
📘 Issue Description
Integrate OpenAI (or similar AI service) for real-time conversation practice functionality. This feature will allow authenticated users to engage in AI-powered conversations to practice their language skills. The implementation should include a secure
/chat/aiPOST endpoint that handles chat requests and responses while maintaining user authentication and proper error handling.🔍 Steps
Backend Implementation
Install OpenAI SDK
openaipackage to dependenciesCreate Chat Controller
src/controllers/chat.controller.tssendMessagemethod for handling chat requestsCreate Chat Service
src/services/chat.service.tsCreate Chat Routes
src/routes/api/modules/chat.routes.tsPOST /api/v1/chat/aiendpointisAuthorized())Create Validation Schema
src/models/validations/chat.validators.tsEnvironment Configuration
OPENAI_API_KEYto environment variablesOPENAI_MODELconfiguration (default: gpt-3.5-turbo)src/core/config/settings.tsError Handling & Security
Database Considerations (Optional Enhancement)
✅ Acceptance Criteria
SuccessResponse,BadRequestResponse)API Specification
Endpoint:
POST /api/v1/chat/aiHeaders:
Authorization:
Bearer <jwt_token>Content-Type:
application/jsonRequest Body:
{ "message": "Hello, I want to practice English conversation", "conversationContext": [], "practiceLevel": "B1", "conversationType": "general" }Success Response (200):
{ "success": true, "message": "Chat response generated successfully", "data": { "response": "Hello! I'd be happy to help you practice English...", "conversationId": "uuid-string", "timestamp": "2024-01-15T10:30:00Z" } }🌎 References
/src/controllers/and/src/services//src/middlewares/authentication.ts/src/models/validations/📜 Additional Notes
Technical Considerations
Integration Points
auth.controller.ts,question.controller.ts)isAuthorized())question.validators.tscore/config/logger.ts