Navya-Sree commited on
Commit
0570c90
·
verified ·
1 Parent(s): 3d841fd

Create llm_utils.py

Browse files
Files changed (1) hide show
  1. src/llm_utils.py +53 -0
src/llm_utils.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/llm_utils.py
2
+ import os
3
+ from openai import OpenAI
4
+
5
+ # You can either:
6
+ # - Set OPENAI_API_KEY as a secret in Hugging Face, OR
7
+ # - Replace "YOUR_OPENAI_API_KEY" directly (less secure)
8
+ API_KEY = os.getenv("OPENAI_API_KEY", "YOUR_OPENAI_API_KEY")
9
+
10
+ client = OpenAI(api_key=API_KEY)
11
+
12
+
13
+ def explain_savings_plan(payload: dict) -> str:
14
+ """
15
+ Calls a small LLM model to explain the numeric savings plan.
16
+ Guardrails:
17
+ - Do NOT invent new numbers
18
+ - Use ONLY fields from payload
19
+ - Explanation-only; no decisions
20
+ """
21
+ system_prompt = """
22
+ You are an AI assistant that explains home down-payment savings plans for first-time buyers.
23
+ You MUST NOT invent or change any numeric values.
24
+ Use ONLY the fields provided in the JSON payload.
25
+ Write 2–3 short sentences that:
26
+ 1) State what the user is trying to achieve (reach a down payment).
27
+ 2) Explain why this recommended monthly savings amount makes sense.
28
+ 3) Mention the timeline (years and months).
29
+ Be neutral, concise, and non-promotional.
30
+ """.strip()
31
+
32
+ user_content = f"Here is the JSON for this user's plan: {payload}"
33
+
34
+ try:
35
+ completion = client.chat.completions.create(
36
+ model="gpt-4.1-mini",
37
+ messages=[
38
+ {"role": "system", "content": system_prompt},
39
+ {"role": "user", "content": user_content},
40
+ ],
41
+ max_tokens=220,
42
+ temperature=0.3,
43
+ )
44
+ explanation = completion.choices[0].message.content.strip()
45
+ return explanation
46
+ except Exception:
47
+ # Safe fallback if LLM fails
48
+ return (
49
+ "We calculated your recommended monthly savings using your home budget, "
50
+ "target down payment percentage, current savings, and chosen timeline. "
51
+ "The remaining amount is spread over the available months, with estimated "
52
+ "closing costs added and expected interest on savings subtracted."
53
+ )