promptrend 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- promptrend-1.0.0/LICENSE +21 -0
- promptrend-1.0.0/PKG-INFO +166 -0
- promptrend-1.0.0/README.md +136 -0
- promptrend-1.0.0/promptrend/__init__.py +6 -0
- promptrend-1.0.0/promptrend/api/routes.py +167 -0
- promptrend-1.0.0/promptrend/app.py +65 -0
- promptrend-1.0.0/promptrend/core/cache.py +65 -0
- promptrend-1.0.0/promptrend/core/config.py +42 -0
- promptrend-1.0.0/promptrend/core/database.py +48 -0
- promptrend-1.0.0/promptrend/core/models.py +49 -0
- promptrend-1.0.0/promptrend/services/error_handler.py +102 -0
- promptrend-1.0.0/promptrend/services/intent_classifier.py +111 -0
- promptrend-1.0.0/promptrend/services/question_generator.py +91 -0
- promptrend-1.0.0/promptrend/services/recommendation_service.py +154 -0
- promptrend-1.0.0/promptrend/services/recommender.py +85 -0
- promptrend-1.0.0/promptrend/utils/helpers.py +13 -0
- promptrend-1.0.0/promptrend.egg-info/PKG-INFO +166 -0
- promptrend-1.0.0/promptrend.egg-info/SOURCES.txt +26 -0
- promptrend-1.0.0/promptrend.egg-info/dependency_links.txt +1 -0
- promptrend-1.0.0/promptrend.egg-info/entry_points.txt +2 -0
- promptrend-1.0.0/promptrend.egg-info/requires.txt +20 -0
- promptrend-1.0.0/promptrend.egg-info/top_level.txt +1 -0
- promptrend-1.0.0/pyproject.toml +44 -0
- promptrend-1.0.0/setup.cfg +4 -0
- promptrend-1.0.0/tests/test_api.py +228 -0
- promptrend-1.0.0/tests/test_integration.py +235 -0
- promptrend-1.0.0/tests/test_intent_classifier.py +12 -0
- promptrend-1.0.0/tests/test_recommender.py +18 -0
promptrend-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Your Name
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: promptrend
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Intent Classification and Contextual Bandit Recommendation System
|
|
5
|
+
Author-email: Your Name <your.email@example.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.8
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: fastapi==0.68.0
|
|
11
|
+
Requires-Dist: uvicorn==0.15.0
|
|
12
|
+
Requires-Dist: pydantic>=2.0.0
|
|
13
|
+
Requires-Dist: pydantic-settings>=2.0.0
|
|
14
|
+
Requires-Dist: python-dotenv==0.19.0
|
|
15
|
+
Requires-Dist: sqlalchemy==1.4.23
|
|
16
|
+
Requires-Dist: psycopg2-binary==2.9.1
|
|
17
|
+
Requires-Dist: redis==4.1.0
|
|
18
|
+
Requires-Dist: torch>=2.0.0
|
|
19
|
+
Requires-Dist: transformers==4.11.3
|
|
20
|
+
Requires-Dist: scikit-learn==0.24.2
|
|
21
|
+
Requires-Dist: numpy==1.21.2
|
|
22
|
+
Requires-Dist: pandas==1.3.3
|
|
23
|
+
Requires-Dist: datasets==1.11.0
|
|
24
|
+
Requires-Dist: accelerate>=0.21.0
|
|
25
|
+
Provides-Extra: test
|
|
26
|
+
Requires-Dist: pytest==6.2.5; extra == "test"
|
|
27
|
+
Requires-Dist: httpx==0.18.2; extra == "test"
|
|
28
|
+
Requires-Dist: pytest-asyncio==0.15.1; extra == "test"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# PrompTrend: Intelligent Chat Support System
|
|
32
|
+
|
|
33
|
+
PrompTrend is an advanced chat support system that combines intent classification and contextual bandit algorithms to provide personalized recommendations and responses. The system uses BERT for intent classification and implements a contextual multi-armed bandit approach for dynamic learning from user interactions.
|
|
34
|
+
|
|
35
|
+
## 🌟 Key Features
|
|
36
|
+
|
|
37
|
+
- Intent classification using BERT
|
|
38
|
+
- Contextual bandit-based recommendation system
|
|
39
|
+
- Real-time user feedback processing
|
|
40
|
+
- Automatic question generation
|
|
41
|
+
- Redis caching for improved performance
|
|
42
|
+
- Comprehensive API documentation
|
|
43
|
+
- Robust error handling
|
|
44
|
+
- Database persistence with PostgreSQL
|
|
45
|
+
|
|
46
|
+
## 🛠️ Technology Stack
|
|
47
|
+
|
|
48
|
+
- **Framework**: FastAPI
|
|
49
|
+
- **ML Models**: BERT (Transformers), T5
|
|
50
|
+
- **Database**: PostgreSQL
|
|
51
|
+
- **Caching**: Redis
|
|
52
|
+
- **ML Libraries**: PyTorch, Scikit-learn
|
|
53
|
+
- **Testing**: Pytest
|
|
54
|
+
- **Documentation**: OpenAPI (Swagger)
|
|
55
|
+
|
|
56
|
+
## 📋 Prerequisites
|
|
57
|
+
|
|
58
|
+
- Python 3.8+
|
|
59
|
+
- PostgreSQL
|
|
60
|
+
- Redis
|
|
61
|
+
- CUDA-compatible GPU (optional, for faster model training)
|
|
62
|
+
|
|
63
|
+
## ⚙️ Installation
|
|
64
|
+
|
|
65
|
+
You can install PrompTrend directly via pip (once published):
|
|
66
|
+
```bash
|
|
67
|
+
pip install promptrend
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
For development, clone the repository and install in editable mode:
|
|
71
|
+
```bash
|
|
72
|
+
git clone https://github.com/yourusername/promptrend.git
|
|
73
|
+
cd promptrend
|
|
74
|
+
pip install -e .[test]
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Set up environment variables:
|
|
78
|
+
```bash
|
|
79
|
+
python scripts/setup_env.py --env development
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## 🚀 Running the Application
|
|
83
|
+
|
|
84
|
+
1. Start the Redis server:
|
|
85
|
+
```bash
|
|
86
|
+
redis-server
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
2. Start the application using the CLI:
|
|
90
|
+
```bash
|
|
91
|
+
promptrend-server
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The API will be available at `http://localhost:8000`
|
|
95
|
+
|
|
96
|
+
## 📚 API Documentation
|
|
97
|
+
|
|
98
|
+
Once the application is running, you can access the interactive API documentation at:
|
|
99
|
+
- Swagger UI: `http://localhost:8000/docs`
|
|
100
|
+
- ReDoc: `http://localhost:8000/redoc`
|
|
101
|
+
|
|
102
|
+
## 🧪 Testing
|
|
103
|
+
|
|
104
|
+
The project includes comprehensive tests for all components. To run the tests:
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
# Run all tests
|
|
108
|
+
pytest
|
|
109
|
+
|
|
110
|
+
# Run tests with coverage report
|
|
111
|
+
pytest --cov=app tests/
|
|
112
|
+
|
|
113
|
+
# Run specific test file
|
|
114
|
+
pytest tests/test_intent_classifier.py
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## 📂 Project Structure
|
|
118
|
+
|
|
119
|
+
```
|
|
120
|
+
promptrend/
|
|
121
|
+
├── api/
|
|
122
|
+
│ └── routes.py # API endpoints
|
|
123
|
+
├── core/
|
|
124
|
+
│ ├── config.py # Configuration management
|
|
125
|
+
│ ├── database.py # Database setup
|
|
126
|
+
│ ├── models.py # Data models
|
|
127
|
+
│ └── cache.py # Redis cache implementation
|
|
128
|
+
├── services/
|
|
129
|
+
│ ├── intent_classifier.py # BERT classifier
|
|
130
|
+
│ ├── recommender.py # Contextual bandit
|
|
131
|
+
│ ├── recommendation_service.py
|
|
132
|
+
│ ├── question_generator.py # T5 question generator
|
|
133
|
+
│ └── error_handler.py # Error handling service
|
|
134
|
+
├── tests/
|
|
135
|
+
│ ├── test_intent_classifier.py
|
|
136
|
+
│ ├── test_recommender.py
|
|
137
|
+
│ ├── test_api.py
|
|
138
|
+
│ └── test_integration.py
|
|
139
|
+
├── scripts/
|
|
140
|
+
│ └── setup_env.py
|
|
141
|
+
├── main.py
|
|
142
|
+
├── requirements.txt
|
|
143
|
+
└── README.md
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## 🤝 Contributing
|
|
147
|
+
|
|
148
|
+
1. Fork the repository
|
|
149
|
+
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
|
|
150
|
+
3. Commit your changes (`git commit -m 'Add amazing feature'`)
|
|
151
|
+
4. Push to the branch (`git push origin feature/amazing-feature`)
|
|
152
|
+
5. Open a Pull Request
|
|
153
|
+
|
|
154
|
+
## 📝 License
|
|
155
|
+
|
|
156
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
157
|
+
|
|
158
|
+
## 🙏 Acknowledgments
|
|
159
|
+
|
|
160
|
+
- Hugging Face for the Transformers library
|
|
161
|
+
- FastAPI team for the amazing framework
|
|
162
|
+
- The open-source community for various dependencies
|
|
163
|
+
|
|
164
|
+
## 📞 Contact
|
|
165
|
+
|
|
166
|
+
For questions and feedback, please create an issue in the GitHub repository.
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# PrompTrend: Intelligent Chat Support System
|
|
2
|
+
|
|
3
|
+
PrompTrend is an advanced chat support system that combines intent classification and contextual bandit algorithms to provide personalized recommendations and responses. The system uses BERT for intent classification and implements a contextual multi-armed bandit approach for dynamic learning from user interactions.
|
|
4
|
+
|
|
5
|
+
## 🌟 Key Features
|
|
6
|
+
|
|
7
|
+
- Intent classification using BERT
|
|
8
|
+
- Contextual bandit-based recommendation system
|
|
9
|
+
- Real-time user feedback processing
|
|
10
|
+
- Automatic question generation
|
|
11
|
+
- Redis caching for improved performance
|
|
12
|
+
- Comprehensive API documentation
|
|
13
|
+
- Robust error handling
|
|
14
|
+
- Database persistence with PostgreSQL
|
|
15
|
+
|
|
16
|
+
## 🛠️ Technology Stack
|
|
17
|
+
|
|
18
|
+
- **Framework**: FastAPI
|
|
19
|
+
- **ML Models**: BERT (Transformers), T5
|
|
20
|
+
- **Database**: PostgreSQL
|
|
21
|
+
- **Caching**: Redis
|
|
22
|
+
- **ML Libraries**: PyTorch, Scikit-learn
|
|
23
|
+
- **Testing**: Pytest
|
|
24
|
+
- **Documentation**: OpenAPI (Swagger)
|
|
25
|
+
|
|
26
|
+
## 📋 Prerequisites
|
|
27
|
+
|
|
28
|
+
- Python 3.8+
|
|
29
|
+
- PostgreSQL
|
|
30
|
+
- Redis
|
|
31
|
+
- CUDA-compatible GPU (optional, for faster model training)
|
|
32
|
+
|
|
33
|
+
## ⚙️ Installation
|
|
34
|
+
|
|
35
|
+
You can install PrompTrend directly via pip (once published):
|
|
36
|
+
```bash
|
|
37
|
+
pip install promptrend
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
For development, clone the repository and install in editable mode:
|
|
41
|
+
```bash
|
|
42
|
+
git clone https://github.com/yourusername/promptrend.git
|
|
43
|
+
cd promptrend
|
|
44
|
+
pip install -e .[test]
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Set up environment variables:
|
|
48
|
+
```bash
|
|
49
|
+
python scripts/setup_env.py --env development
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## 🚀 Running the Application
|
|
53
|
+
|
|
54
|
+
1. Start the Redis server:
|
|
55
|
+
```bash
|
|
56
|
+
redis-server
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
2. Start the application using the CLI:
|
|
60
|
+
```bash
|
|
61
|
+
promptrend-server
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The API will be available at `http://localhost:8000`
|
|
65
|
+
|
|
66
|
+
## 📚 API Documentation
|
|
67
|
+
|
|
68
|
+
Once the application is running, you can access the interactive API documentation at:
|
|
69
|
+
- Swagger UI: `http://localhost:8000/docs`
|
|
70
|
+
- ReDoc: `http://localhost:8000/redoc`
|
|
71
|
+
|
|
72
|
+
## 🧪 Testing
|
|
73
|
+
|
|
74
|
+
The project includes comprehensive tests for all components. To run the tests:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
# Run all tests
|
|
78
|
+
pytest
|
|
79
|
+
|
|
80
|
+
# Run tests with coverage report
|
|
81
|
+
pytest --cov=app tests/
|
|
82
|
+
|
|
83
|
+
# Run specific test file
|
|
84
|
+
pytest tests/test_intent_classifier.py
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## 📂 Project Structure
|
|
88
|
+
|
|
89
|
+
```
|
|
90
|
+
promptrend/
|
|
91
|
+
├── api/
|
|
92
|
+
│ └── routes.py # API endpoints
|
|
93
|
+
├── core/
|
|
94
|
+
│ ├── config.py # Configuration management
|
|
95
|
+
│ ├── database.py # Database setup
|
|
96
|
+
│ ├── models.py # Data models
|
|
97
|
+
│ └── cache.py # Redis cache implementation
|
|
98
|
+
├── services/
|
|
99
|
+
│ ├── intent_classifier.py # BERT classifier
|
|
100
|
+
│ ├── recommender.py # Contextual bandit
|
|
101
|
+
│ ├── recommendation_service.py
|
|
102
|
+
│ ├── question_generator.py # T5 question generator
|
|
103
|
+
│ └── error_handler.py # Error handling service
|
|
104
|
+
├── tests/
|
|
105
|
+
│ ├── test_intent_classifier.py
|
|
106
|
+
│ ├── test_recommender.py
|
|
107
|
+
│ ├── test_api.py
|
|
108
|
+
│ └── test_integration.py
|
|
109
|
+
├── scripts/
|
|
110
|
+
│ └── setup_env.py
|
|
111
|
+
├── main.py
|
|
112
|
+
├── requirements.txt
|
|
113
|
+
└── README.md
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## 🤝 Contributing
|
|
117
|
+
|
|
118
|
+
1. Fork the repository
|
|
119
|
+
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
|
|
120
|
+
3. Commit your changes (`git commit -m 'Add amazing feature'`)
|
|
121
|
+
4. Push to the branch (`git push origin feature/amazing-feature`)
|
|
122
|
+
5. Open a Pull Request
|
|
123
|
+
|
|
124
|
+
## 📝 License
|
|
125
|
+
|
|
126
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
127
|
+
|
|
128
|
+
## 🙏 Acknowledgments
|
|
129
|
+
|
|
130
|
+
- Hugging Face for the Transformers library
|
|
131
|
+
- FastAPI team for the amazing framework
|
|
132
|
+
- The open-source community for various dependencies
|
|
133
|
+
|
|
134
|
+
## 📞 Contact
|
|
135
|
+
|
|
136
|
+
For questions and feedback, please create an issue in the GitHub repository.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
from .services.intent_classifier import IntentClassifier
|
|
2
|
+
from .services.recommender import ContextualBandit as Recommender
|
|
3
|
+
from .services.question_generator import QuestionGenerator
|
|
4
|
+
|
|
5
|
+
__version__ = "1.0.0"
|
|
6
|
+
__all__ = ["IntentClassifier", "Recommender", "QuestionGenerator"]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends
|
|
2
|
+
from typing import List, Optional
|
|
3
|
+
from promptrend.core.models import (
|
|
4
|
+
RecommendationRequest,
|
|
5
|
+
RecommendationResponse,
|
|
6
|
+
TrainingRequest,
|
|
7
|
+
TrainingResponse,
|
|
8
|
+
IntentClassifierConfig,
|
|
9
|
+
FeedbackRequest,
|
|
10
|
+
FeedbackResponse
|
|
11
|
+
)
|
|
12
|
+
from promptrend.services.intent_classifier import IntentClassifier
|
|
13
|
+
from promptrend.services.recommender import ContextualBandit
|
|
14
|
+
from promptrend.services.recommendation_service import RecommendationService
|
|
15
|
+
from sqlalchemy.orm import Session
|
|
16
|
+
from promptrend.core.database import get_db
|
|
17
|
+
import logging
|
|
18
|
+
|
|
19
|
+
# Configure logging
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
# Create router
|
|
23
|
+
router = APIRouter()
|
|
24
|
+
|
|
25
|
+
# Initialize services
|
|
26
|
+
intent_classifier = None
|
|
27
|
+
bandit = ContextualBandit()
|
|
28
|
+
recommendation_service = RecommendationService()
|
|
29
|
+
|
|
30
|
+
@router.post("/initialize", response_model=dict)
|
|
31
|
+
async def initialize_classifier(config: IntentClassifierConfig):
|
|
32
|
+
"""Initialize or load the intent classifier"""
|
|
33
|
+
global intent_classifier
|
|
34
|
+
try:
|
|
35
|
+
logger.info(f"Initializing classifier with config: {config}")
|
|
36
|
+
intent_classifier = IntentClassifier(
|
|
37
|
+
model_path=config.model_path,
|
|
38
|
+
num_labels=config.num_labels,
|
|
39
|
+
use_pretrained=config.use_pretrained
|
|
40
|
+
)
|
|
41
|
+
return {"status": "success", "message": "Classifier initialized"}
|
|
42
|
+
except Exception as e:
|
|
43
|
+
logger.error(f"Failed to initialize classifier: {str(e)}")
|
|
44
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
45
|
+
|
|
46
|
+
@router.post("/feedback", response_model=FeedbackResponse)
|
|
47
|
+
async def store_feedback(
|
|
48
|
+
request: FeedbackRequest,
|
|
49
|
+
db: Session = Depends(get_db)
|
|
50
|
+
):
|
|
51
|
+
"""Store and process user feedback for recommendations"""
|
|
52
|
+
try:
|
|
53
|
+
logger.info(f"Storing feedback for user {request.user_id}, recommendation {request.recommendation_id}")
|
|
54
|
+
await recommendation_service.store_feedback(
|
|
55
|
+
db=db,
|
|
56
|
+
user_id=request.user_id,
|
|
57
|
+
recommendation_id=request.recommendation_id,
|
|
58
|
+
feedback_score=request.feedback_score
|
|
59
|
+
)
|
|
60
|
+
return FeedbackResponse(status="success", message="Feedback stored successfully")
|
|
61
|
+
except Exception as e:
|
|
62
|
+
logger.error(f"Failed to store feedback: {str(e)}")
|
|
63
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
64
|
+
|
|
65
|
+
@router.post("/train", response_model=TrainingResponse)
|
|
66
|
+
async def train_classifier(request: TrainingRequest, background_tasks: BackgroundTasks):
|
|
67
|
+
"""Train the classifier with new data"""
|
|
68
|
+
global intent_classifier
|
|
69
|
+
|
|
70
|
+
if not request.training_data:
|
|
71
|
+
raise HTTPException(status_code=400, detail="Training data cannot be empty")
|
|
72
|
+
|
|
73
|
+
if intent_classifier is None:
|
|
74
|
+
raise HTTPException(status_code=400, detail="Classifier not initialized")
|
|
75
|
+
|
|
76
|
+
# Validate training data before queuing
|
|
77
|
+
labels = [item.label for item in request.training_data]
|
|
78
|
+
num_labels = intent_classifier.model.config.num_labels
|
|
79
|
+
if any(label < 0 or label >= num_labels for label in labels):
|
|
80
|
+
raise HTTPException(
|
|
81
|
+
status_code=400,
|
|
82
|
+
detail=f"Labels must be between 0 and {num_labels - 1}"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
logger.info(f"Starting training with {len(request.training_data)} examples for {request.epochs} epochs")
|
|
87
|
+
# Convert training data to the format expected by IntentClassifier
|
|
88
|
+
formatted_training_data = [
|
|
89
|
+
{"text": item.text, "label": item.label}
|
|
90
|
+
for item in request.training_data
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
background_tasks.add_task(
|
|
94
|
+
intent_classifier.train,
|
|
95
|
+
formatted_training_data,
|
|
96
|
+
request.epochs
|
|
97
|
+
)
|
|
98
|
+
return TrainingResponse(status="success", message="Training started in background")
|
|
99
|
+
except Exception as e:
|
|
100
|
+
logger.error(f"Failed to train classifier: {str(e)}")
|
|
101
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
102
|
+
|
|
103
|
+
@router.post("/recommendations", response_model=RecommendationResponse)
|
|
104
|
+
async def get_recommendations(request: RecommendationRequest, db: Session = Depends(get_db)):
|
|
105
|
+
"""Get recommendations based on chat history and generate relevant questions"""
|
|
106
|
+
global intent_classifier
|
|
107
|
+
|
|
108
|
+
if not request.chat_history.messages:
|
|
109
|
+
raise HTTPException(
|
|
110
|
+
status_code=400,
|
|
111
|
+
detail="Chat history cannot be empty"
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
if intent_classifier is None:
|
|
115
|
+
raise HTTPException(status_code=400, detail="Classifier not initialized")
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
logger.info(f"Getting recommendations for user {request.user_id}")
|
|
119
|
+
|
|
120
|
+
# Classify intents
|
|
121
|
+
intents_and_scores = [
|
|
122
|
+
intent_classifier.classify(msg.content)
|
|
123
|
+
for msg in request.chat_history.messages
|
|
124
|
+
]
|
|
125
|
+
|
|
126
|
+
intents, confidence_scores = zip(*intents_and_scores)
|
|
127
|
+
|
|
128
|
+
# Get context vector
|
|
129
|
+
context = bandit.get_context_vector(
|
|
130
|
+
request.user_id,
|
|
131
|
+
[msg.content for msg in request.chat_history.messages],
|
|
132
|
+
list(confidence_scores)
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
# Use default categories if none provided
|
|
136
|
+
categories = request.categories or ["general", "technical", "support"]
|
|
137
|
+
|
|
138
|
+
# Get recommendations from service
|
|
139
|
+
result = await recommendation_service.get_recommendations(
|
|
140
|
+
db=db,
|
|
141
|
+
user_id=request.user_id,
|
|
142
|
+
chat_history=[msg.dict() for msg in request.chat_history.messages],
|
|
143
|
+
categories=categories,
|
|
144
|
+
num_recommendations=request.num_recommendations
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
# Generate questions using the question generator
|
|
148
|
+
from promptrend.services.question_generator import QuestionGenerator
|
|
149
|
+
question_generator = QuestionGenerator()
|
|
150
|
+
generated_questions = question_generator.generate_questions(
|
|
151
|
+
result["recommendations"],
|
|
152
|
+
[msg.content for msg in request.chat_history.messages],
|
|
153
|
+
num_questions=request.num_recommendations
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
# Add recommendation_ids to result if not present
|
|
157
|
+
if "recommendation_ids" not in result:
|
|
158
|
+
result["recommendation_ids"] = []
|
|
159
|
+
|
|
160
|
+
# Include generated questions in response
|
|
161
|
+
result["generated_questions"] = generated_questions
|
|
162
|
+
|
|
163
|
+
return RecommendationResponse(**result)
|
|
164
|
+
|
|
165
|
+
except Exception as e:
|
|
166
|
+
logger.error(f"Failed to get recommendations: {str(e)}")
|
|
167
|
+
raise HTTPException(status_code=500, detail=str(e))
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
from fastapi import FastAPI
|
|
2
|
+
from promptrend.api.routes import router as api_router # Note the import alias
|
|
3
|
+
from promptrend.core.config import get_settings
|
|
4
|
+
from promptrend.core.database import init_db
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
# Configure logging
|
|
9
|
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TF logging
|
|
10
|
+
logging.getLogger('tensorflow').setLevel(logging.ERROR)
|
|
11
|
+
logging.basicConfig(level=logging.INFO)
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
# Get app settings
|
|
15
|
+
settings = get_settings()
|
|
16
|
+
|
|
17
|
+
# Initialize FastAPI app
|
|
18
|
+
app = FastAPI(
|
|
19
|
+
title="PrompTrend API",
|
|
20
|
+
description="Intent Classification and Contextual Bandit Recommendation System",
|
|
21
|
+
version="1.0.0",
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
# Setup middleware for exception handling
|
|
25
|
+
from fastapi import Request
|
|
26
|
+
from fastapi.responses import JSONResponse
|
|
27
|
+
from promptrend.services.error_handler import PrompTrendError, handle_error
|
|
28
|
+
|
|
29
|
+
@app.middleware("http")
|
|
30
|
+
async def handle_exceptions(request: Request, call_next):
|
|
31
|
+
try:
|
|
32
|
+
return await call_next(request)
|
|
33
|
+
except ValueError as e:
|
|
34
|
+
return JSONResponse(
|
|
35
|
+
status_code=400,
|
|
36
|
+
content={"detail": str(e)}
|
|
37
|
+
)
|
|
38
|
+
except PrompTrendError as e:
|
|
39
|
+
return handle_error(e)
|
|
40
|
+
except Exception as e:
|
|
41
|
+
logger.error(f"Unhandled exception: {str(e)}")
|
|
42
|
+
return JSONResponse(
|
|
43
|
+
status_code=500,
|
|
44
|
+
content={"detail": str(e)}
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
# Include API router with proper prefix
|
|
48
|
+
app.include_router(api_router, prefix=settings.API_V1_STR)
|
|
49
|
+
|
|
50
|
+
# Initialize database
|
|
51
|
+
@app.on_event("startup")
|
|
52
|
+
def startup_event():
|
|
53
|
+
try:
|
|
54
|
+
logger.info("Initializing database...")
|
|
55
|
+
init_db()
|
|
56
|
+
logger.info("Database initialized successfully")
|
|
57
|
+
except Exception as e:
|
|
58
|
+
logger.error(f"Failed to initialize database: {str(e)}")
|
|
59
|
+
|
|
60
|
+
def start():
|
|
61
|
+
import uvicorn
|
|
62
|
+
uvicorn.run("promptrend.app:app", host="0.0.0.0", port=8000, reload=True)
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
start()
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# core/cache.py
|
|
2
|
+
import redis
|
|
3
|
+
from typing import Optional, Any, Dict
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from functools import wraps
|
|
7
|
+
|
|
8
|
+
class RedisCache:
|
|
9
|
+
def __init__(self):
|
|
10
|
+
self.redis_url = os.getenv("REDIS_URL", "redis://localhost:6379/0")
|
|
11
|
+
self.redis_client = redis.from_url(self.redis_url)
|
|
12
|
+
self.default_ttl = 3600 # 1 hour default TTL
|
|
13
|
+
|
|
14
|
+
def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:
|
|
15
|
+
"""Set a value in cache with optional TTL"""
|
|
16
|
+
try:
|
|
17
|
+
serialized_value = json.dumps(value)
|
|
18
|
+
return self.redis_client.set(
|
|
19
|
+
key,
|
|
20
|
+
serialized_value,
|
|
21
|
+
ex=ttl or self.default_ttl
|
|
22
|
+
)
|
|
23
|
+
except Exception as e:
|
|
24
|
+
print(f"Cache set error: {str(e)}")
|
|
25
|
+
return False
|
|
26
|
+
|
|
27
|
+
def get(self, key: str) -> Optional[Any]:
|
|
28
|
+
"""Get a value from cache"""
|
|
29
|
+
try:
|
|
30
|
+
value = self.redis_client.get(key)
|
|
31
|
+
return json.loads(value) if value else None
|
|
32
|
+
except Exception as e:
|
|
33
|
+
print(f"Cache get error: {str(e)}")
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
def delete(self, key: str) -> bool:
|
|
37
|
+
"""Delete a value from cache"""
|
|
38
|
+
try:
|
|
39
|
+
return bool(self.redis_client.delete(key))
|
|
40
|
+
except Exception as e:
|
|
41
|
+
print(f"Cache delete error: {str(e)}")
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
# Cache decorator
|
|
45
|
+
def cached(ttl: Optional[int] = None):
|
|
46
|
+
def decorator(func):
|
|
47
|
+
@wraps(func)
|
|
48
|
+
async def wrapper(*args, **kwargs):
|
|
49
|
+
cache = RedisCache()
|
|
50
|
+
|
|
51
|
+
# Create cache key from function name and arguments
|
|
52
|
+
cache_key = f"{func.__name__}:{str(args)}:{str(kwargs)}"
|
|
53
|
+
|
|
54
|
+
# Try to get from cache
|
|
55
|
+
cached_result = cache.get(cache_key)
|
|
56
|
+
if cached_result is not None:
|
|
57
|
+
return cached_result
|
|
58
|
+
|
|
59
|
+
# If not in cache, execute function and cache result
|
|
60
|
+
result = await func(*args, **kwargs)
|
|
61
|
+
cache.set(cache_key, result, ttl)
|
|
62
|
+
return result
|
|
63
|
+
|
|
64
|
+
return wrapper
|
|
65
|
+
return decorator
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# core/config.py
|
|
2
|
+
from pydantic_settings import BaseSettings
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
from typing import Optional
|
|
5
|
+
import os
|
|
6
|
+
from dotenv import load_dotenv
|
|
7
|
+
|
|
8
|
+
# Load .env file
|
|
9
|
+
load_dotenv()
|
|
10
|
+
|
|
11
|
+
class Settings(BaseSettings):
|
|
12
|
+
# Database
|
|
13
|
+
DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@localhost:5432/promptrend")
|
|
14
|
+
|
|
15
|
+
# Redis
|
|
16
|
+
REDIS_URL: str = os.getenv("REDIS_URL", "redis://localhost:6379/0")
|
|
17
|
+
REDIS_TTL: int = 3600 # Cache TTL in seconds
|
|
18
|
+
|
|
19
|
+
# Model
|
|
20
|
+
MODEL_PATH: str = os.getenv("MODEL_PATH", "bert-base-uncased")
|
|
21
|
+
NUM_LABELS: int = 10
|
|
22
|
+
USE_PRETRAINED: bool = True
|
|
23
|
+
|
|
24
|
+
# API
|
|
25
|
+
API_V1_STR: str = "/api/v1"
|
|
26
|
+
PROJECT_NAME: str = "PrompTrend"
|
|
27
|
+
|
|
28
|
+
# Environment
|
|
29
|
+
ENVIRONMENT: str = os.getenv("ENVIRONMENT", "development")
|
|
30
|
+
DEBUG: bool = ENVIRONMENT == "development"
|
|
31
|
+
|
|
32
|
+
# Logging
|
|
33
|
+
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
|
34
|
+
|
|
35
|
+
class Config:
|
|
36
|
+
env_file = ".env"
|
|
37
|
+
case_sensitive = True
|
|
38
|
+
|
|
39
|
+
@lru_cache()
|
|
40
|
+
def get_settings() -> Settings:
|
|
41
|
+
"""Get cached settings"""
|
|
42
|
+
return Settings()
|