Commit
·
f0d81d7
1
Parent(s):
a005924
Switch to ChatCompletion for OpenAI
Browse files- app/smart_recommendation.py +11 -17
app/smart_recommendation.py
CHANGED
|
@@ -5,22 +5,15 @@ from collections import defaultdict
|
|
| 5 |
from datetime import datetime, timedelta
|
| 6 |
from typing import Dict, List
|
| 7 |
|
|
|
|
| 8 |
from dotenv import load_dotenv
|
| 9 |
-
from openai import OpenAI
|
| 10 |
|
| 11 |
from app.models import BudgetRecommendation, CategoryExpense
|
| 12 |
|
| 13 |
load_dotenv()
|
| 14 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
if not OPENAI_API_KEY:
|
| 18 |
-
return None
|
| 19 |
-
try:
|
| 20 |
-
return OpenAI(api_key=OPENAI_API_KEY)
|
| 21 |
-
except Exception as exc:
|
| 22 |
-
print(f"OpenAI client initialization failed: {exc}")
|
| 23 |
-
return None
|
| 24 |
|
| 25 |
class SmartBudgetRecommender:
|
| 26 |
"""
|
|
@@ -32,7 +25,6 @@ class SmartBudgetRecommender:
|
|
| 32 |
|
| 33 |
def __init__(self, db):
|
| 34 |
self.db = db
|
| 35 |
-
self.openai_client = _build_openai_client()
|
| 36 |
|
| 37 |
def get_recommendations(self, user_id: str, month: int, year: int) -> List[BudgetRecommendation]:
|
| 38 |
"""
|
|
@@ -246,7 +238,7 @@ class SmartBudgetRecommender:
|
|
| 246 |
|
| 247 |
def _get_ai_recommendation(self, category: str, data: Dict, avg_expense: float, fallback_budget: float):
|
| 248 |
"""Use OpenAI to refine the budget recommendation."""
|
| 249 |
-
if not
|
| 250 |
return None
|
| 251 |
|
| 252 |
history = ", ".join(f"{value:.0f}" for value in data["monthly_values"])
|
|
@@ -270,13 +262,15 @@ class SmartBudgetRecommender:
|
|
| 270 |
)
|
| 271 |
|
| 272 |
try:
|
| 273 |
-
response =
|
| 274 |
-
model="gpt-
|
| 275 |
-
input=prompt,
|
| 276 |
temperature=0.1,
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
| 278 |
)
|
| 279 |
-
content = response.
|
| 280 |
return json.loads(content)
|
| 281 |
except Exception as exc:
|
| 282 |
print(f"OpenAI recommendation error for {category}: {exc}")
|
|
|
|
| 5 |
from datetime import datetime, timedelta
|
| 6 |
from typing import Dict, List
|
| 7 |
|
| 8 |
+
import openai
|
| 9 |
from dotenv import load_dotenv
|
|
|
|
| 10 |
|
| 11 |
from app.models import BudgetRecommendation, CategoryExpense
|
| 12 |
|
| 13 |
load_dotenv()
|
| 14 |
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 15 |
+
if OPENAI_API_KEY:
|
| 16 |
+
openai.api_key = OPENAI_API_KEY
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
class SmartBudgetRecommender:
|
| 19 |
"""
|
|
|
|
| 25 |
|
| 26 |
def __init__(self, db):
|
| 27 |
self.db = db
|
|
|
|
| 28 |
|
| 29 |
def get_recommendations(self, user_id: str, month: int, year: int) -> List[BudgetRecommendation]:
|
| 30 |
"""
|
|
|
|
| 238 |
|
| 239 |
def _get_ai_recommendation(self, category: str, data: Dict, avg_expense: float, fallback_budget: float):
|
| 240 |
"""Use OpenAI to refine the budget recommendation."""
|
| 241 |
+
if not OPENAI_API_KEY:
|
| 242 |
return None
|
| 243 |
|
| 244 |
history = ", ".join(f"{value:.0f}" for value in data["monthly_values"])
|
|
|
|
| 262 |
)
|
| 263 |
|
| 264 |
try:
|
| 265 |
+
response = openai.ChatCompletion.create(
|
| 266 |
+
model="gpt-4o-mini",
|
|
|
|
| 267 |
temperature=0.1,
|
| 268 |
+
messages=[
|
| 269 |
+
{"role": "system", "content": "You are an Indian personal finance coach who outputs JSON."},
|
| 270 |
+
{"role": "user", "content": prompt},
|
| 271 |
+
],
|
| 272 |
)
|
| 273 |
+
content = response.choices[0].message["content"]
|
| 274 |
return json.loads(content)
|
| 275 |
except Exception as exc:
|
| 276 |
print(f"OpenAI recommendation error for {category}: {exc}")
|