Spaces:
Sleeping
Sleeping
Create llm_utils.py
Browse files- llm_utils.py +57 -0
llm_utils.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# llm_utils.py
|
| 2 |
+
import os
|
| 3 |
+
from openai import OpenAI
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# Option 1 (recommended): set OPENAI_API_KEY in Hugging Face Secrets
|
| 7 |
+
API_KEY = os.getenv("OPENAI_API_KEY", "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")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
client = OpenAI(api_key=API_KEY)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def explain_savings_plan(payload: dict) -> str:
|
| 14 |
+
"""
|
| 15 |
+
Uses a small LLM model to turn numeric savings plan outputs into a
|
| 16 |
+
short, plain-English explanation.
|
| 17 |
+
|
| 18 |
+
The LLM:
|
| 19 |
+
- MUST NOT invent new numbers
|
| 20 |
+
- Only rephrases the fields in payload
|
| 21 |
+
- Does not change the calculation, only explains it
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
system_prompt = """
|
| 25 |
+
You are an AI assistant that explains mortgage down-payment savings plans.
|
| 26 |
+
You MUST NOT invent any new numbers.
|
| 27 |
+
Use ONLY the fields provided in the JSON payload.
|
| 28 |
+
Write 2–3 short sentences that:
|
| 29 |
+
1) State what the user is trying to achieve (reach a down payment).
|
| 30 |
+
2) Explain why this recommended monthly savings amount makes sense.
|
| 31 |
+
3) Mention the timeline (years and months).
|
| 32 |
+
Be neutral, clear, and non-promotional.
|
| 33 |
+
""".strip()
|
| 34 |
+
|
| 35 |
+
# We send the raw payload as JSON text in the user message.
|
| 36 |
+
user_content = f"Here is the JSON for this user's plan: {payload}"
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
completion = client.chat.completions.create(
|
| 40 |
+
model="gpt-4.1-mini",
|
| 41 |
+
messages=[
|
| 42 |
+
{"role": "system", "content": system_prompt},
|
| 43 |
+
{"role": "user", "content": user_content},
|
| 44 |
+
],
|
| 45 |
+
max_tokens=200,
|
| 46 |
+
temperature=0.3,
|
| 47 |
+
)
|
| 48 |
+
explanation = completion.choices[0].message.content.strip()
|
| 49 |
+
return explanation
|
| 50 |
+
except Exception as e:
|
| 51 |
+
# Fallback if LLM fails
|
| 52 |
+
return (
|
| 53 |
+
"We calculated your recommended monthly savings based on your home budget, "
|
| 54 |
+
"target down payment %, current savings, and chosen timeline. "
|
| 55 |
+
"The amount spreads your remaining down-payment need over the available months, "
|
| 56 |
+
"adding estimated closing costs and subtracting expected interest earnings."
|
| 57 |
+
)
|