# 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

```env
# 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 cases
- `gpt-4` - More advanced reasoning, higher quality suggestions
- `gpt-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:**
```json
{
  "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 for
- `count` (optional, integer): Number of suggestions to generate (1-10, default: 5)

**Response:**
```json
{
  "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):**
```json
{
  "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

```javascript
const aiService = require('./services/aiService');
```

### Generate Task Suggestions

```javascript
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

```javascript
if (aiService.isAvailable()) {
  // Use AI-powered suggestions
} else {
  // Use mock suggestions or alternative logic
}
```

### Get Service Status

```javascript
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:

1. **Context Building**: Includes street name, location, and relevant historical data
2. **Past Tasks Analysis**: Avoids suggesting recently completed tasks
3. **Weather Awareness**: Suggests weather-appropriate activities
4. **Community Alignment**: Prioritizes tasks aligned with community goals
5. **Safety Focus**: Emphasizes tasks safe for volunteers without specialized equipment
6. **Structured Output**: Requests JSON format with specific fields

## Error Handling

The service implements comprehensive error handling:

1. **API Failures**: Automatically falls back to mock suggestions
2. **Timeout Protection**: 10-second timeout on API requests
3. **Response Parsing**: Handles various response formats (including markdown code blocks)
4. **Validation**: Ensures all suggestions have required fields
5. **Logging**: Detailed error logging for debugging

## Testing

Run the AI service tests:

```bash
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

1. **Cache Suggestions**: Consider caching suggestions for frequently requested streets
2. **Rate Limiting**: Implement rate limiting to control API costs
3. **Batch Processing**: Generate suggestions for multiple streets in batches when possible
4. **Monitor Usage**: Track OpenAI API usage and costs
5. **Fallback Strategy**: Always have mock suggestions available as fallback
6. **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-turbo` instead of `gpt-4`
- Implement caching for frequently requested streets
- Add rate limiting to the endpoint
- Reduce `numberOfSuggestions` parameter

## 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
