Implement real OpenAI integration for the AI task suggestions feature: - Create aiService.js with GPT-3.5/GPT-4 integration - Add context-aware prompt engineering (street data, past tasks, weather, priorities) - Implement automatic fallback to high-quality mock suggestions - Add graceful degradation when API key not configured - Create comprehensive error handling and timeout protection - Add input validation with aiValidator middleware - Implement /api/ai/status endpoint for service monitoring - Add 12 passing test cases covering all functionality - Document OpenAI model configuration in .env.example - Create detailed AI_SERVICE.md documentation Key features: - Uses axios to call OpenAI API directly (no SDK dependency) - Analyzes street conditions and past 30 days of completed tasks - Generates structured JSON responses with task metadata - 10-second timeout with automatic fallback - Comprehensive logging using centralized logger service - Returns warnings when running in mock mode All tests pass (12/12). Ready for production use with or without API key. 🤖 Generated with AI Assistant Co-Authored-By: AI Assistant <noreply@ai-assistant.com>
7.2 KiB
AI Service Documentation
Overview
The AI Service provides intelligent task suggestions for street maintenance using OpenAI's GPT models. It analyzes street conditions, historical data, weather patterns, and community priorities to generate contextually relevant and actionable maintenance tasks.
Features
- Context-Aware Suggestions: Generates tasks based on street name, location, and past maintenance history
- Weather Integration: Considers current weather conditions for appropriate task suggestions
- Community Priorities: Aligns suggestions with community goals and priorities
- Fallback Mode: Automatically falls back to high-quality mock suggestions if OpenAI API is unavailable
- Graceful Degradation: Works without API key configuration, providing mock data with warnings
Configuration
Environment Variables
# Required for AI features
OPENAI_API_KEY=sk-your-api-key-here
# Optional - defaults to gpt-3.5-turbo
OPENAI_MODEL=gpt-3.5-turbo
Available Models:
gpt-3.5-turbo(default) - Fast, cost-effective, good for most use casesgpt-4- More advanced reasoning, higher quality suggestionsgpt-4-turbo-preview- Latest GPT-4 with improved performance
Cost Considerations
- gpt-3.5-turbo: ~$0.001-0.002 per request (typical task suggestion)
- gpt-4: ~$0.03-0.06 per request
- Each task suggestion request typically uses 500-1000 tokens
API Endpoints
Check AI Service Status
GET /api/ai/status
Returns the current status of the AI service.
Headers:
x-auth-token: <jwt-token>
Response:
{
"success": true,
"data": {
"configured": true,
"model": "gpt-3.5-turbo",
"status": "active"
}
}
Get Task Suggestions
GET /api/ai/task-suggestions
Generate AI-powered task suggestions for street maintenance.
Headers:
x-auth-token: <jwt-token>
Query Parameters:
streetId(optional, string): ID of the specific street to get suggestions forcount(optional, integer): Number of suggestions to generate (1-10, default: 5)
Response:
{
"success": true,
"data": [
{
"street": "Main Street",
"description": "Remove litter from sidewalk",
"details": "Improves neighborhood appearance and prevents storm drain blockage.",
"estimatedTime": 30,
"difficulty": "easy",
"priority": "medium",
"source": "ai"
}
],
"meta": {
"source": "ai",
"count": 5,
"aiConfigured": true
}
}
Response (without API key):
{
"success": true,
"data": [...],
"meta": {
"source": "mock",
"count": 5,
"aiConfigured": false
},
"warning": "OpenAI API not configured. Returning mock suggestions. Set OPENAI_API_KEY in environment variables for AI-powered suggestions."
}
Service Usage
Import the Service
const aiService = require('./services/aiService');
Generate Task Suggestions
const suggestions = await aiService.generateTaskSuggestions({
streetName: "Main Street",
location: {
type: "Point",
coordinates: [-122.4194, 37.7749]
},
pastTasks: [
"Remove graffiti from wall",
"Clear storm drains"
],
weather: {
condition: "Partly cloudy",
description: "Clear with mild temperatures",
temperature: 72
},
communityPriorities: [
"Safety improvements",
"Environmental sustainability"
],
numberOfSuggestions: 5
});
Check Service Availability
if (aiService.isAvailable()) {
// Use AI-powered suggestions
} else {
// Use mock suggestions or alternative logic
}
Get Service Status
const status = aiService.getStatus();
// Returns: { configured: boolean, model: string, status: string }
Suggestion Structure
Each task suggestion includes:
- street (string): Name of the street
- description (string): Brief, actionable task description (2-8 words)
- details (string): Explanation of why the task is important (1 sentence)
- estimatedTime (number): Estimated completion time in minutes
- difficulty (string): Task difficulty - "easy", "moderate", or "hard"
- priority (string): Task priority - "low", "medium", or "high"
- source (string): Source of suggestion - "ai" or "mock"
Prompt Engineering
The AI service uses carefully crafted prompts to generate high-quality suggestions:
- Context Building: Includes street name, location, and relevant historical data
- Past Tasks Analysis: Avoids suggesting recently completed tasks
- Weather Awareness: Suggests weather-appropriate activities
- Community Alignment: Prioritizes tasks aligned with community goals
- Safety Focus: Emphasizes tasks safe for volunteers without specialized equipment
- Structured Output: Requests JSON format with specific fields
Error Handling
The service implements comprehensive error handling:
- API Failures: Automatically falls back to mock suggestions
- Timeout Protection: 10-second timeout on API requests
- Response Parsing: Handles various response formats (including markdown code blocks)
- Validation: Ensures all suggestions have required fields
- Logging: Detailed error logging for debugging
Testing
Run the AI service tests:
npm test -- __tests__/routes/ai.test.js
Test coverage includes:
- Service status endpoint
- Task suggestion generation (with and without street ID)
- Input validation
- Mock mode functionality
- Error handling and fallbacks
- Service integration tests
Best Practices
- Cache Suggestions: Consider caching suggestions for frequently requested streets
- Rate Limiting: Implement rate limiting to control API costs
- Batch Processing: Generate suggestions for multiple streets in batches when possible
- Monitor Usage: Track OpenAI API usage and costs
- Fallback Strategy: Always have mock suggestions available as fallback
- User Feedback: Collect feedback on suggestion quality to improve prompts
Troubleshooting
Issue: "OpenAI API not configured" warning
Solution: Set OPENAI_API_KEY environment variable with your OpenAI API key.
Issue: Suggestions are not contextual
Solution: Ensure you're passing street details, location, and past tasks to the service.
Issue: API timeout errors
Solution: Check network connectivity to OpenAI API. The service will automatically fall back to mock suggestions.
Issue: High API costs
Solution:
- Use
gpt-3.5-turboinstead ofgpt-4 - Implement caching for frequently requested streets
- Add rate limiting to the endpoint
- Reduce
numberOfSuggestionsparameter
Future Enhancements
Potential improvements to the AI service:
- Integration with real-time weather APIs
- Machine learning on task completion rates
- Seasonal task suggestions
- User preference learning
- Image analysis for street condition assessment
- Multi-language support
- Integration with city planning APIs
- Automated task prioritization based on urgency
Support
For issues or questions:
- Check logs at
backend/server.log - Review error messages in the response
- Ensure environment variables are correctly set
- Verify OpenAI API key is valid and has sufficient credits