Spaces:
Build error
Build error
Create chain_problems.py
Browse files- chain_problems.py +44 -0
chain_problems.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# chain_problems.py
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Dict
|
| 5 |
+
from langchain import PromptTemplate, LLMChain
|
| 6 |
+
from models import chat_model
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
problem_prompt_template = PromptTemplate(
|
| 11 |
+
input_variables=["responses", "internal_report"],
|
| 12 |
+
template=(
|
| 13 |
+
"You are a wellness analyst. You have the following user responses to health-related questions:\n"
|
| 14 |
+
"{responses}\n\n"
|
| 15 |
+
"You also have an internal analysis report:\n"
|
| 16 |
+
"{internal_report}\n\n"
|
| 17 |
+
"From these inputs, determine a 'problem severity percentage' for the user in the following areas: "
|
| 18 |
+
"sleep, exercise, stress, and diet. "
|
| 19 |
+
"Return your answer in JSON format with keys: sleep_problem, exercise_problem, stress_problem, diet_problem.\n"
|
| 20 |
+
"Ensure severity percentages are numbers from 0 to 100.\n\n"
|
| 21 |
+
"JSON Output:"
|
| 22 |
+
)
|
| 23 |
+
)
|
| 24 |
+
problem_chain = LLMChain(llm=chat_model, prompt=problem_prompt_template)
|
| 25 |
+
|
| 26 |
+
def analyze_problems_with_chain(responses: Dict[str, str], internal_report: str) -> Dict[str, float]:
|
| 27 |
+
responses_str = "\n".join(f"{q}: {a}" for q, a in responses.items())
|
| 28 |
+
raw_text = problem_chain.run(responses=responses_str, internal_report=internal_report)
|
| 29 |
+
try:
|
| 30 |
+
start_idx = raw_text.find('{')
|
| 31 |
+
end_idx = raw_text.rfind('}') + 1
|
| 32 |
+
json_str = raw_text[start_idx:end_idx]
|
| 33 |
+
problems = json.loads(json_str)
|
| 34 |
+
for key in ["sleep_problem", "exercise_problem", "stress_problem", "diet_problem"]:
|
| 35 |
+
problems.setdefault(key, 0.0)
|
| 36 |
+
return {k: float(v) for k, v in problems.items()}
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.error(f"Error parsing problem percentages from LLM: {e}")
|
| 39 |
+
return {
|
| 40 |
+
"sleep_problem": 0.0,
|
| 41 |
+
"exercise_problem": 0.0,
|
| 42 |
+
"stress_problem": 0.0,
|
| 43 |
+
"diet_problem": 0.0
|
| 44 |
+
}
|