rivapereira123 commited on
Commit
9f88c37
Β·
verified Β·
1 Parent(s): 8eed257

Update scenario_builder.py

Browse files
Files changed (1) hide show
  1. scenario_builder.py +58 -61
scenario_builder.py CHANGED
@@ -6,7 +6,7 @@ from typing import Dict, Any, List
6
  class ScenarioNode:
7
  def __init__(self, question: str, options: Dict[str, Any], correct_answer: str = None, feedback: str = None):
8
  self.question = question
9
- self.options = options # {label: next_node_id or action_fn_name}
10
  self.correct_answer = correct_answer
11
  self.feedback = feedback
12
 
@@ -23,75 +23,72 @@ class ScenarioBuilder:
23
  self.ai_engine = ai_engine
24
  self.scenarios = {}
25
 
26
- import json
27
-
28
  async def create_scenario_from_query(self, query: str, num_questions: int = 5) -> Dict[str, Any]:
29
- prompt = f"""
30
- Based on the medical query: '{query}', generate a {num_questions}-question interactive medical training scenario.
31
- Each question must have 4 options (A, B, C, D), a correct answer (A|B|C|D), and a feedback explanation.
32
- Format the response as a **valid JSON array** of objects, like:
33
- [
34
- {{
35
- "question": "string",
36
- "options": {{
37
- "A": "string",
38
- "B": "string",
39
- "C": "string",
40
- "D": "string"
41
- }},
42
- "correct_answer": "A",
43
- "feedback": "string"
44
- }}
45
- ]
46
- ⚠️ Respond ONLY with valid JSON.
47
- ❌ DO NOT include markdown (like ```json) or extra explanation or commentary.
48
- βœ… Output MUST be a raw JSON array. No formatting, no headings, no intro text.
49
- """
50
 
51
- try:
52
- response = self.ai_engine.generate_raw_text(prompt)
53
- scenario_data_str = response.strip()
54
 
55
- if scenario_data_str.startswith("```"):
56
- scenario_data_str = re.sub(r"^```(?:json)?", "", scenario_data_str)
57
- scenario_data_str = re.sub(r"```$", "", scenario_data_str).strip()
58
 
59
- print("πŸ§ͺ Raw AI response preview:", scenario_data_str[:200])
60
 
61
- scenario_questions = json.loads(scenario_data_str)
62
 
63
- scenario_nodes = []
64
- for q in scenario_questions:
65
- node = ScenarioNode(
66
- question=q['question'],
67
- options=q['options'],
68
- correct_answer=q['correct_answer'],
69
- feedback=q['feedback']
70
- )
71
- scenario_nodes.append(node)
72
 
73
- scenario_id = hashlib.md5(query.encode()).hexdigest()
74
- self.scenarios[scenario_id] = scenario_nodes
75
 
76
- return {
77
- "scenario_id": scenario_id,
78
- "questions": [node.to_dict() for node in scenario_nodes]
79
- }
80
-
81
- except json.JSONDecodeError as e:
82
- print(f"❌ JSON decode failed: {e}")
83
- print(f"πŸ“¦ Full AI Output:\n{scenario_data_str[:500]}")
84
- return {
85
- "error": "Failed to parse AI-generated scenario. Invalid JSON format.",
86
- "details": str(e)
87
- }
88
- except Exception as e:
89
- print(f"❌ Scenario generation error: {e}")
90
- return {
91
- "error": "Failed to generate scenario.",
92
- "details": str(e)
93
- }
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  def get_scenario(self, scenario_id: str) -> List[ScenarioNode]:
97
  return self.scenarios.get(scenario_id)
 
6
  class ScenarioNode:
7
  def __init__(self, question: str, options: Dict[str, Any], correct_answer: str = None, feedback: str = None):
8
  self.question = question
9
+ self.options = options
10
  self.correct_answer = correct_answer
11
  self.feedback = feedback
12
 
 
23
  self.ai_engine = ai_engine
24
  self.scenarios = {}
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)
91
+ }
92
 
93
  def get_scenario(self, scenario_id: str) -> List[ScenarioNode]:
94
  return self.scenarios.get(scenario_id)