rivapereira123 commited on
Commit
a00e395
·
verified ·
1 Parent(s): 9f88c37

Update scenario_builder.py

Browse files
Files changed (1) hide show
  1. scenario_builder.py +53 -39
scenario_builder.py CHANGED
@@ -25,66 +25,80 @@ class ScenarioBuilder:
25
 
26
  async def create_scenario_from_query(self, query: str, num_questions: int = 5) -> Dict[str, Any]:
27
  prompt = f"""
28
- Based on the medical query: '{query}', generate a {num_questions}-question interactive medical training scenario.
29
- Each question must have 4 options (A, B, C, D), a correct answer (A|B|C|D), and a feedback explanation.
30
- Format the response as a **valid JSON array** of objects, like:
31
- [
32
- {{
33
- "question": "string",
34
- "options": {{
35
- "A": "string",
36
- "B": "string",
37
- "C": "string",
38
- "D": "string"
39
- }},
40
- "correct_answer": "A",
41
- "feedback": "string"
42
- }}
43
- ]
44
- ⚠️ Respond ONLY with valid JSON.
45
- DO NOT include markdown (like ```json) or extra explanation or commentary.
46
- Output MUST be a raw JSON array. No formatting, no headings, no intro text.
47
- """
 
 
 
 
 
 
 
 
48
 
49
  try:
50
- response = self.ai_engine.generate_raw_text(prompt)
51
- scenario_data_str = response.strip()
 
 
 
52
 
53
- if scenario_data_str.startswith("```"):
54
- scenario_data_str = re.sub(r"^```(?:json)?", "", scenario_data_str)
55
- scenario_data_str = re.sub(r"```$", "", scenario_data_str).strip()
 
56
 
57
- print("🧪 Raw AI response preview:", scenario_data_str[:200])
58
 
59
- scenario_questions = json.loads(scenario_data_str)
60
 
61
- scenario_nodes = []
62
- for q in scenario_questions:
 
63
  node = ScenarioNode(
64
- question=q['question'],
65
- options=q['options'],
66
- correct_answer=q['correct_answer'],
67
- feedback=q['feedback']
68
  )
69
- scenario_nodes.append(node)
70
 
71
  scenario_id = hashlib.md5(query.encode()).hexdigest()
72
- self.scenarios[scenario_id] = scenario_nodes
73
 
74
  return {
75
  "scenario_id": scenario_id,
76
- "questions": [node.to_dict() for node in scenario_nodes]
77
  }
78
 
79
  except json.JSONDecodeError as e:
80
- print(f"❌ JSON decode failed: {e}")
81
- print(f"📦 Full AI Output:\n{scenario_data_str[:500]}")
82
  return {
83
  "error": "Failed to parse AI-generated scenario. Invalid JSON format.",
84
  "details": str(e)
85
  }
 
86
  except Exception as e:
87
- print(f"❌ Scenario generation error: {e}")
88
  return {
89
  "error": "Failed to generate scenario.",
90
  "details": str(e)
 
25
 
26
  async def create_scenario_from_query(self, query: str, num_questions: int = 5) -> Dict[str, Any]:
27
  prompt = f"""
28
+ You are a medical training assistant.
29
+
30
+ Based on the topic: "{query}", generate a {num_questions}-question interactive medical scenario. Each question must have:
31
+
32
+ - a `question` (string)
33
+ - an `options` object with keys "A""D"
34
+ - a `correct_answer` ("A", "B", "C", or "D")
35
+ - a `feedback` string
36
+
37
+ Respond ONLY with this exact JSON format:
38
+
39
+ [
40
+ {{
41
+ "question": "...",
42
+ "options": {{
43
+ "A": "...",
44
+ "B": "...",
45
+ "C": "...",
46
+ "D": "..."
47
+ }},
48
+ "correct_answer": "A|B|C|D",
49
+ "feedback": "..."
50
+ }},
51
+ ...
52
+ ]
53
+
54
+ ⚠️ No markdown. No prose. No headings. Just valid JSON array. Your job is to act like a JSON API.
55
+ """
56
 
57
  try:
58
+ # Use Groq for accurate structure
59
+ raw_response = self.ai_engine._generate_with_groq(
60
+ query=query,
61
+ refined_prompt=prompt
62
+ )
63
 
64
+ # Clean any wrapping or garbage
65
+ start = raw_response.find("[")
66
+ end = raw_response.rfind("]") + 1
67
+ json_block = raw_response[start:end].strip()
68
 
69
+ print("🧪 Raw Groq output preview:", json_block[:200])
70
 
71
+ scenario_data = json.loads(json_block)
72
 
73
+ # Turn into ScenarioNode objects
74
+ nodes = []
75
+ for q in scenario_data:
76
  node = ScenarioNode(
77
+ question=q["question"],
78
+ options=q["options"],
79
+ correct_answer=q["correct_answer"],
80
+ feedback=q["feedback"]
81
  )
82
+ nodes.append(node)
83
 
84
  scenario_id = hashlib.md5(query.encode()).hexdigest()
85
+ self.scenarios[scenario_id] = nodes
86
 
87
  return {
88
  "scenario_id": scenario_id,
89
+ "questions": [n.to_dict() for n in nodes]
90
  }
91
 
92
  except json.JSONDecodeError as e:
93
+ print("❌ JSON parse error:", e)
94
+ print("⚠️ Raw Groq output:", raw_response[:500])
95
  return {
96
  "error": "Failed to parse AI-generated scenario. Invalid JSON format.",
97
  "details": str(e)
98
  }
99
+
100
  except Exception as e:
101
+ print("❌ Scenario generation error:", e)
102
  return {
103
  "error": "Failed to generate scenario.",
104
  "details": str(e)