Automated Action 97c002ac88 Add AI-powered chat-to-tasks feature
Implement a new endpoint that converts natural language input into structured tasks using an LLM. Features include:
- LLM service abstraction with support for OpenAI and Google Gemini
- Dependency injection pattern for easy provider switching
- Robust error handling and response formatting
- Integration with existing user authentication and task creation
- Fallback to mock LLM service for testing or development
2025-05-17 07:44:19 +00:00

314 lines
11 KiB
Markdown

# Task Manager API
A RESTful API for managing tasks, built with FastAPI and SQLite.
## Features
- User authentication with JWT tokens
- User registration and login
- Task CRUD operations with user-based access control
- Task status and priority management
- Task completion tracking
- AI-powered chat-to-tasks conversion
- API documentation with Swagger UI and ReDoc
- Health endpoint for monitoring
## Tech Stack
- FastAPI: Modern, high-performance web framework for building APIs
- SQLAlchemy: SQL toolkit and Object-Relational Mapping (ORM)
- Alembic: Database migration tool
- SQLite: Lightweight relational database
- Pydantic: Data validation and settings management
- Uvicorn: ASGI server for FastAPI applications
- JWT: JSON Web Tokens for authentication
- Passlib: Password hashing and verification
- Python-Jose: Python implementation of JWT
- OpenAI/Google Gemini API: AI models for natural language processing
- HTTPX: Async HTTP client for API requests
## API Endpoints
### API Information
- `GET /`: Get API information and available endpoints
### Authentication
- `POST /auth/register`: Register a new user
- `POST /auth/login`: Login to get access token
- `GET /auth/me`: Get current user information
- `POST /auth/test-token`: Test if the access token is valid
### Task Management (requires authentication)
- `GET /tasks`: Get all tasks for the current user
- `POST /tasks`: Create a new task for the current user
- `GET /tasks/{task_id}`: Get a specific task for the current user
- `PUT /tasks/{task_id}`: Update a task for the current user
- `DELETE /tasks/{task_id}`: Delete a task for the current user
- `POST /tasks/{task_id}/complete`: Mark a task as completed for the current user
### AI-Powered Task Creation (requires authentication)
- `POST /chat/chat-to-tasks`: Convert natural language input into structured tasks
### Health and Diagnostic Endpoints
- `GET /health`: Application health check
- `GET /db-test`: Database connection diagnostic endpoint
## Example Curl Commands
### Register a new user
```bash
curl -X 'POST' \
'https://taskmanagerapi-ttkjqk.backend.im/auth/register' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"email": "user@example.com",
"username": "testuser",
"password": "password123"
}'
```
### Login to get access token
```bash
curl -X 'POST' \
'https://taskmanagerapi-ttkjqk.backend.im/auth/login' \
-H 'accept: application/json' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'username=user@example.com&password=password123'
```
### Create a new task (with authentication)
```bash
curl -X 'POST' \
'https://taskmanagerapi-ttkjqk.backend.im/tasks/' \
-H 'accept: application/json' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"title": "Complete project documentation",
"description": "Write comprehensive documentation for the project",
"priority": "high",
"status": "todo",
"due_date": "2023-06-30T18:00:00.000Z",
"completed": false
}'
```
### Get all tasks (with authentication)
```bash
curl -X 'GET' \
'https://taskmanagerapi-ttkjqk.backend.im/tasks/' \
-H 'accept: application/json' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
```
### Get a specific task (with authentication)
```bash
curl -X 'GET' \
'https://taskmanagerapi-ttkjqk.backend.im/tasks/1' \
-H 'accept: application/json' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
```
### Update a task (with authentication)
```bash
curl -X 'PUT' \
'https://taskmanagerapi-ttkjqk.backend.im/tasks/1' \
-H 'accept: application/json' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"title": "Updated title",
"description": "Updated description",
"status": "in_progress"
}'
```
### Delete a task (with authentication)
```bash
curl -X 'DELETE' \
'https://taskmanagerapi-ttkjqk.backend.im/tasks/1' \
-H 'accept: application/json' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
```
### Mark a task as completed (with authentication)
```bash
curl -X 'POST' \
'https://taskmanagerapi-ttkjqk.backend.im/tasks/1/complete' \
-H 'accept: application/json' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
```
### Create tasks from natural language (with authentication)
```bash
curl -X 'POST' \
'https://taskmanagerapi-ttkjqk.backend.im/chat/chat-to-tasks' \
-H 'accept: application/json' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"message": "I need to prepare a presentation for Monday, pick up groceries tomorrow, and call John about the project by Friday."
}'
```
### Get current user information (with authentication)
```bash
curl -X 'GET' \
'https://taskmanagerapi-ttkjqk.backend.im/auth/me' \
-H 'accept: application/json' \
-H 'Authorization: Bearer YOUR_ACCESS_TOKEN'
```
## Project Structure
```
taskmanagerapi/
├── alembic/ # Database migrations
│ └── versions/ # Migration scripts
├── app/
│ ├── api/ # API endpoints
│ │ ├── deps.py # Dependency injection for authentication
│ │ └── routers/ # API route definitions
│ │ ├── auth.py # Authentication endpoints
│ │ ├── chat.py # Chat-to-tasks endpoints
│ │ └── tasks.py # Task management endpoints
│ ├── core/ # Core application code
│ │ ├── config.py # Application configuration
│ │ └── security.py # Security utilities (JWT, password hashing)
│ ├── crud/ # CRUD operations
│ │ ├── base.py # Base CRUD operations
│ │ ├── task.py # Task CRUD operations
│ │ └── user.py # User CRUD operations
│ ├── db/ # Database setup
│ │ ├── base.py # Base imports for models
│ │ ├── base_class.py # Base class for SQLAlchemy models
│ │ ├── init_db.py # Database initialization
│ │ └── session.py # Database session management
│ ├── models/ # SQLAlchemy models
│ │ ├── task.py # Task model
│ │ └── user.py # User model
│ ├── schemas/ # Pydantic schemas/models
│ │ ├── chat.py # Chat-to-tasks schemas
│ │ ├── task.py # Task schemas
│ │ └── user.py # User and authentication schemas
│ └── services/ # Service integrations
│ └── llm_service.py # LLM service for chat-to-tasks conversion
├── main.py # Application entry point
└── requirements.txt # Project dependencies
```
## Database Configuration
The application is configured to use SQLite with the following database locations (in order of priority):
1. Path defined in the `DB_PATH` environment variable (if set)
2. `/app/storage/db/db.sqlite` (primary production path)
3. `/app/storage/db.sqlite` (alternate storage path)
4. `./storage/db/db.sqlite` (local development)
5. `/tmp/taskmanager/db.sqlite` (fallback)
The application automatically selects the first available and writable location from this list.
### Enhanced Database Reliability
The application includes several features to ensure robust and reliable database operations:
1. **Multi-path discovery**: Automatically finds and uses the first writable database location
2. **Directory creation**: Creates database directories if they don't exist
3. **Database initialization**: Initializes the database with required tables using both SQLAlchemy and direct SQLite
4. **Connection retry logic**: Automatically retries database connections with exponential backoff
5. **SQLite optimizations**: Uses WAL journal mode and other SQLite performance optimizations
6. **Error diagnostic logging**: Comprehensive error logging for easier troubleshooting
7. **Fallback mechanisms**: Falls back to direct SQLite operations if SQLAlchemy fails
### Alembic Migration Enhancements
Alembic migrations include robust error handling and initialization:
1. **Pre-migration checks**: Verifies database directories exist and are writable
2. **Auto-creation**: Creates necessary directories and initializes the database file
3. **Retry logic**: Implements retry logic for migration operations
4. **Detailed diagnostics**: Provides detailed error information for failed migrations
## Getting Started
### Installation
1. Clone the repository
2. Install dependencies:
```
pip install -r requirements.txt
```
### Running Migrations
```
alembic upgrade head
```
The migration process will automatically:
1. Create the database directory if it doesn't exist
2. Initialize the database file if needed
3. Apply all migrations with retry logic for reliability
### Starting the Application
```
uvicorn main:app --reload
```
The API will be available at http://localhost:8000
### Default Admin User
During initialization, the system creates a default admin user:
- Email: admin@example.com
- Username: admin
- Password: adminpassword
You can use these credentials to authenticate and get started right away.
### Authentication Flow
1. **Register a new user**: Send a POST request to `/auth/register` with email, username, and password
2. **Login**: Send a POST request to `/auth/login` with username/email and password to receive an access token
3. **Use token**: Include the token in your requests as a Bearer token in the Authorization header
4. **Access protected endpoints**: Use the token to access protected task management endpoints
### Chat-to-Tasks Feature
The application includes an AI-powered feature that converts natural language inputs into structured task objects:
1. **Environment Configuration**: Set the `LLM_PROVIDER` environment variable to select the AI model provider:
- `openai`: Uses OpenAI's GPT models (requires `OPENAI_API_KEY` and optionally `OPENAI_MODEL`)
- `gemini`: Uses Google's Gemini models (requires `GEMINI_API_KEY` and optionally `GEMINI_MODEL`)
- `mock`: Uses a simple rule-based mock implementation (default, no API keys needed)
2. **Using the Feature**: Send a POST request to `/chat/chat-to-tasks` with a natural language message describing your tasks. The API will:
- Process the message using the configured AI model
- Extract task details (title, description, due date, priority)
- Create tasks in the database for the authenticated user
- Return the created tasks in a structured format
3. **Example**: "I need to finish the report by Friday, call Susan about the meeting tomorrow morning, and buy groceries tonight" will be converted into three separate tasks with appropriate details.
### API Documentation
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc