LogicGoInfotechSpaces commited on
Commit
9db7520
·
verified ·
1 Parent(s): 02858b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -16
app.py CHANGED
@@ -2,11 +2,11 @@
2
  """
3
  Financial Health Score Service (FastAPI)
4
 
5
- Fully updated version:
6
- - Uses GPT-4o-mini with strict JSON schema output
 
7
  - Correct OpenAI Chat Completions API
8
- - Fully valid `.choices[0].message.parsed`
9
- - Bulletproof Mongo fetch + normalization
10
  """
11
 
12
  import json
@@ -97,10 +97,7 @@ def normalize_transactions(txns):
97
  out = []
98
  for txn in txns:
99
  date_val = txn.get("date")
100
- if isinstance(date_val, datetime):
101
- date_str = date_val.date().isoformat()
102
- else:
103
- date_str = None
104
 
105
  # Resolve currency
106
  currency_code = None
@@ -140,10 +137,10 @@ You are a financial wellness expert. Use the user's budgets and last 30 days of
140
  to compute a financial health score from 0 to 100.
141
 
142
  Rules:
143
- - When mentioning amounts, ALWAYS prefix with currency code when available (e.g., "INR 10,000").
144
  - Keep explanation short (1–2 sentences).
145
- - Score must reflect spending habits, budget usage, and financial balance.
146
- - Respond ONLY using the JSON schema enforced below.
147
 
148
  Budgets:
149
  {json.dumps(budgets, indent=2)}
@@ -193,7 +190,7 @@ def financial_score(payload: ScoreRequest):
193
  prompt = build_prompt(budgets, transactions)
194
 
195
  # ===========================
196
- # STRICT GPT-4o-mini JSON SCHEMA
197
  # ===========================
198
  try:
199
  response = openai.chat.completions.create(
@@ -222,18 +219,30 @@ def financial_score(payload: ScoreRequest):
222
  except Exception as exc:
223
  raise HTTPException(status_code=502, detail=f"OpenAI request failed: {exc}")
224
 
225
- # SAFE PARSE JSON
226
- # SAFE PARSE JSON (latest OpenAI format)
 
227
  try:
228
- raw_json = response.choices[0].message.content[0].text
 
 
 
 
 
 
 
 
 
 
 
229
  parsed = json.loads(raw_json)
 
230
  except Exception as e:
231
  raise HTTPException(
232
  status_code=502,
233
  detail=f"Could not parse JSON output: {e}"
234
  )
235
 
236
-
237
  # Score normalization
238
  score_val = parsed.get("score", 0)
239
  try:
 
2
  """
3
  Financial Health Score Service (FastAPI)
4
 
5
+ FINAL VERSION:
6
+ - Uses GPT-4o-mini with JSON schema
7
+ - Universal-safe JSON parsing (supports all SDK formats)
8
  - Correct OpenAI Chat Completions API
9
+ - Bulletproof error handling
 
10
  """
11
 
12
  import json
 
97
  out = []
98
  for txn in txns:
99
  date_val = txn.get("date")
100
+ date_str = date_val.date().isoformat() if isinstance(date_val, datetime) else None
 
 
 
101
 
102
  # Resolve currency
103
  currency_code = None
 
137
  to compute a financial health score from 0 to 100.
138
 
139
  Rules:
140
+ - ALWAYS prefix currency amounts with currency code (e.g., "INR 10,000").
141
  - Keep explanation short (1–2 sentences).
142
+ - Score must reflect spending, budget control, and overall balance.
143
+ - Respond ONLY in the JSON schema required below.
144
 
145
  Budgets:
146
  {json.dumps(budgets, indent=2)}
 
190
  prompt = build_prompt(budgets, transactions)
191
 
192
  # ===========================
193
+ # GPT-4o-mini WITH JSON SCHEMA
194
  # ===========================
195
  try:
196
  response = openai.chat.completions.create(
 
219
  except Exception as exc:
220
  raise HTTPException(status_code=502, detail=f"OpenAI request failed: {exc}")
221
 
222
+ # ===========================
223
+ # UNIVERSAL JSON PARSING (supports ALL SDK formats)
224
+ # ===========================
225
  try:
226
+ content = response.choices[0].message.content
227
+
228
+ # Case A — list of dicts (new SDK)
229
+ if isinstance(content, list):
230
+ raw_json = content[0].get("text", content[0])
231
+ else:
232
+ # Case B — plain string (older SDK)
233
+ raw_json = content
234
+
235
+ if not isinstance(raw_json, str):
236
+ raw_json = str(raw_json)
237
+
238
  parsed = json.loads(raw_json)
239
+
240
  except Exception as e:
241
  raise HTTPException(
242
  status_code=502,
243
  detail=f"Could not parse JSON output: {e}"
244
  )
245
 
 
246
  # Score normalization
247
  score_val = parsed.get("score", 0)
248
  try: