File size: 44,278 Bytes
38ca196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62055c0
38ca196
 
dde2b11
38ca196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09354cb
 
38ca196
7cc6733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38ca196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2368b95
dde2b11
 
 
2368b95
dde2b11
 
 
 
 
 
 
 
 
2368b95
dde2b11
 
 
2368b95
dde2b11
 
 
 
 
38ca196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dde2b11
38ca196
 
 
 
dde2b11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38ca196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2368b95
38ca196
 
 
 
2368b95
38ca196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae74888
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38ca196
dde2b11
38ca196
dde2b11
38ca196
 
 
dde2b11
 
 
38ca196
 
 
 
 
 
 
ae74888
 
 
38ca196
 
dde2b11
 
 
ae74888
38ca196
 
dde2b11
ae74888
38ca196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dde2b11
38ca196
 
 
 
 
 
 
 
 
2368b95
 
 
 
 
 
 
 
38ca196
 
 
 
 
 
 
 
 
 
09354cb
38ca196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dde2b11
38ca196
 
 
 
 
 
dde2b11
38ca196
 
 
 
 
 
 
 
 
 
 
dde2b11
 
 
 
 
 
 
 
38ca196
 
 
dde2b11
 
 
 
 
 
 
 
 
 
 
 
38ca196
 
 
dde2b11
 
38ca196
dde2b11
38ca196
 
dde2b11
38ca196
 
 
 
dde2b11
 
 
 
 
 
 
38ca196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9a32ad5-9f07-47f2-97ae-15b0646e355b",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp clinical_tutor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0db4b759-310c-4e38-9fdc-2efb94b541dd",
   "metadata": {},
   "source": [
    "# Clinical Tutor\n",
    "\n",
    "> Core module for using learning context for context-appropriate tutor responses\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16f93992-88dd-409b-8370-b86302e1ce6a",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d2403bb-70a1-4744-be0b-d259234c1b62",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "from nbdev.showdoc import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "477ba22b-55c1-467e-8206-a92f88a598fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "from typing import Dict, List, Optional, Tuple, Any, AsyncGenerator\n",
    "import os\n",
    "import json\n",
    "import logging\n",
    "import asyncio\n",
    "import uuid\n",
    "from datetime import datetime\n",
    "from pathlib import Path\n",
    "import aiohttp\n",
    "from pydantic import BaseModel\n",
    "from dotenv import load_dotenv\n",
    "from wardbuddy.learning_context import LearningContext, setup_logger, LearningCategory, SmartGoal, RotationContext\n",
    "\n",
    "\n",
    "# Load environment variables\n",
    "load_dotenv()\n",
    "\n",
    "logger = setup_logger(__name__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7da445d7-7f51-44d5-b027-e2cf65c79069",
   "metadata": {},
   "source": [
    "## Adaptive Clinical Tutor"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58d76615-480c-4fe4-9d4a-e67dd892132a",
   "metadata": {},
   "source": [
    "This module implements:\n",
    "\n",
    " - Engages in natural case discussions like a clinical supervisor\n",
    " - Provides context-aware feedback based on student's rotation and preferences\n",
    " - Analyzes discussions to track learning progress\n",
    " - Integrates with the student's learning context\n",
    "\n",
    "The tutor aims to mimic real-world clinical teaching interactions where students present cases and receive feedback in a natural conversational style.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da7d2115-b30f-40ba-9566-bcbaf155026d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export \n",
    "class OpenRouterException(Exception):\n",
    "    \"\"\"Custom exception for OpenRouter API errors\"\"\"\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1956b74-a5fe-4b69-9b5c-efe4cc55b97d",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class ClinicalTutor:\n",
    "    \"\"\"\n",
    "    Clinical teaching system using LLMs for goal setting and case discussion.\n",
    "    \n",
    "    Features:\n",
    "    - SMART goal generation\n",
    "    - Case discussion\n",
    "    - Progress tracking\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(\n",
    "        self,\n",
    "        context_path: Optional[Path] = None,\n",
    "        model: str = \"anthropic/claude-3-sonnet\",\n",
    "        api_key: Optional[str] = None\n",
    "    ):\n",
    "        \"\"\"\n",
    "        Initialize clinical tutor.\n",
    "        \n",
    "        Args:\n",
    "            context_path: Path for context persistence\n",
    "            model: OpenRouter model identifier\n",
    "            api_key: OpenRouter API key (falls back to env var)\n",
    "        \"\"\"\n",
    "        self.api_key = api_key or os.getenv(\"OPENROUTER_API_KEY\")\n",
    "        if not self.api_key:\n",
    "            raise ValueError(\"OpenRouter API key required\")\n",
    "            \n",
    "        self.api_url = \"https://openrouter.ai/api/v1/chat/completions\"\n",
    "        self.model = model\n",
    "        \n",
    "        self.learning_context = LearningContext(context_path)\n",
    "        \n",
    "        # Track current discussion\n",
    "        self.current_discussion: List[Dict[str, str]] = []\n",
    "    \n",
    "        logger.info(\"Clinical tutor initialized\")\n",
    "\n",
    "    async def _get_completion(\n",
    "        self,\n",
    "        messages: List[Dict],\n",
    "        temperature: float = 0.7,\n",
    "        max_retries: int = 3\n",
    "    ) -> str:\n",
    "        \"\"\"\n",
    "        Get completion from OpenRouter API with retry logic.\n",
    "        \n",
    "        Args:\n",
    "            messages: List of conversation messages\n",
    "            temperature: Temperature for response generation\n",
    "            max_retries: Maximum retry attempts\n",
    "            \n",
    "        Returns:\n",
    "            str: Model response\n",
    "            \n",
    "        Raises:\n",
    "            OpenRouterException: If API calls fail after retries\n",
    "        \"\"\"\n",
    "        headers = {\n",
    "            \"Authorization\": f\"Bearer {self.api_key}\",\n",
    "            \"Content-Type\": \"application/json\",\n",
    "            \"HTTP-Referer\": \"http://localhost:7860\"\n",
    "        }\n",
    "        \n",
    "        data = {\n",
    "            \"model\": self.model,\n",
    "            \"messages\": messages,\n",
    "            \"temperature\": temperature,\n",
    "            \"max_tokens\": 2000\n",
    "        }\n",
    "        \n",
    "        for attempt in range(max_retries):\n",
    "            try:\n",
    "                async with aiohttp.ClientSession() as session:\n",
    "                    async with session.post(\n",
    "                        self.api_url,\n",
    "                        headers=headers,\n",
    "                        json=data,\n",
    "                        timeout=30\n",
    "                    ) as response:\n",
    "                        response.raise_for_status()\n",
    "                        result = await response.json()\n",
    "                        return result[\"choices\"][0][\"message\"][\"content\"]\n",
    "                        \n",
    "            except Exception as e:\n",
    "                if attempt == max_retries - 1:\n",
    "                    raise OpenRouterException(f\"API call failed: {str(e)}\")\n",
    "                logger.warning(f\"Retry {attempt + 1} after error: {str(e)}\")\n",
    "                await asyncio.sleep(1 * (attempt + 1))  # Exponential backoff\n",
    "    \n",
    "    async def generate_smart_goals(\n",
    "        self,\n",
    "        specialty: str,\n",
    "        setting: str,\n",
    "        num_goals: int = 3\n",
    "    ) -> List[SmartGoal]:\n",
    "        \"\"\"\n",
    "        Generate SMART goals for rotation context.\n",
    "        \n",
    "        Args:\n",
    "            specialty: Medical specialty\n",
    "            setting: Clinical setting\n",
    "            num_goals: Number of goals to generate\n",
    "            \n",
    "        Returns:\n",
    "            list: Generated SMART goals\n",
    "        \"\"\"\n",
    "        prompt = f\"\"\"Generate {num_goals} specific learning goals for a medical trainee in {specialty} ({setting}).\n",
    "    \n",
    "    For each goal:\n",
    "    1. Select an appropriate category from: {', '.join(cat.value for cat in LearningCategory)}\n",
    "    2. Write a specific, measurable goal that builds clinical competence. Write the specific goal only for the next case discussion (i.e. it is not longitudinal across several cases). Also, this goal needs to be able to be evaluated by you - there is limited access to doctors to verify facts. \n",
    "    \n",
    "    Format as JSON array with fields:\n",
    "    - category: Learning category name\n",
    "    - smart_version: SMART formatted goal text\n",
    "    \n",
    "    For example:\n",
    "    [\n",
    "      {{\n",
    "        \"category\": \"Clinical Reasoning\",\n",
    "        \"smart_version\": \"Identify a comprehensive list of differential diagnoses for a patient with acute shortness of breath.\"\n",
    "      }},\n",
    "      {{\n",
    "        \"category\": \"Management\",\n",
    "        \"smart_version\": \"Outline a detailed management plan for a patient with heart failure.\"\n",
    "      }}\n",
    "    ]\n",
    "    \n",
    "    Goals should be specific to the {setting} setting in {specialty}.\"\"\"\n",
    "    \n",
    "        try:\n",
    "            response = await self._get_completion([{\n",
    "                \"role\": \"system\",\n",
    "                \"content\": prompt\n",
    "            }])\n",
    "            \n",
    "            # Parse response to extract goals\n",
    "            goals_data = json.loads(response)\n",
    "            \n",
    "            # Convert to SmartGoal objects\n",
    "            goals = []\n",
    "            for data in goals_data:\n",
    "                goal = SmartGoal(\n",
    "                    id=f\"goal_{uuid.uuid4()}\",\n",
    "                    category=LearningCategory(data[\"category\"]),\n",
    "                    original_input=\"\",  # Auto-generated\n",
    "                    smart_version=data[\"smart_version\"],\n",
    "                    specialty=specialty,\n",
    "                    setting=setting,\n",
    "                    created_at=datetime.now()\n",
    "                )\n",
    "                goals.append(goal)\n",
    "            \n",
    "            logger.info(f\"Generated {len(goals)} SMART goals\")\n",
    "            return goals\n",
    "            \n",
    "        except Exception as e:\n",
    "            logger.error(f\"Error generating goals: {str(e)}\")\n",
    "            # Instead of returning empty list, generate some default goals\n",
    "            default_goals = [\n",
    "                SmartGoal(\n",
    "                    id=f\"goal_{uuid.uuid4()}\",\n",
    "                    category=LearningCategory.CLINICAL_REASONING,\n",
    "                    original_input=\"\",\n",
    "                    smart_version=f\"Develop systematic approach to common {specialty} presentations in {setting} setting\",\n",
    "                    specialty=specialty,\n",
    "                    setting=setting,\n",
    "                    created_at=datetime.now()\n",
    "                ),\n",
    "                SmartGoal(\n",
    "                    id=f\"goal_{uuid.uuid4()}\",\n",
    "                    category=LearningCategory.MANAGEMENT,\n",
    "                    original_input=\"\",\n",
    "                    smart_version=f\"Create evidence-based management plans for basic {specialty} conditions\",\n",
    "                    specialty=specialty,\n",
    "                    setting=setting,\n",
    "                    created_at=datetime.now()\n",
    "                )\n",
    "            ]\n",
    "            return default_goals\n",
    "        \n",
    "    async def generate_smart_goal(\n",
    "        self,\n",
    "        user_input: str,\n",
    "        specialty: str,\n",
    "        setting: str\n",
    "    ) -> Optional[SmartGoal]:\n",
    "        \"\"\"\n",
    "        Generate SMART goal from user input.\n",
    "        \n",
    "        Args:\n",
    "            user_input: User's goal description\n",
    "            specialty: Current specialty\n",
    "            setting: Current setting\n",
    "            \n",
    "        Returns:\n",
    "            SmartGoal: Generated SMART goal\n",
    "        \"\"\"\n",
    "        prompt = f\"\"\"Convert this learning goal into a more specific goal (Specific, Measurable, Achievable, Relevant) for a patient in {specialty} ({setting}):\n",
    "\n",
    "\"{user_input}\"\n",
    "\n",
    "1. Select the most appropriate category from: {', '.join(cat.value for cat in LearningCategory)}\n",
    "2. Rewrite as a specific goal specific to {setting} in {specialty}\n",
    "\n",
    "Format as JSON with fields:\n",
    "- category: Learning category name\n",
    "- smart_version: SMART formatted goal text\"\"\"\n",
    "\n",
    "        try:\n",
    "            response = await self._get_completion([{\n",
    "                \"role\": \"system\",\n",
    "                \"content\": prompt\n",
    "            }])\n",
    "            \n",
    "            # Parse response\n",
    "            data = json.loads(response)\n",
    "            \n",
    "            return SmartGoal(\n",
    "                id=f\"goal_{uuid.uuid4()}\",\n",
    "                category=LearningCategory(data[\"category\"]),\n",
    "                original_input=user_input,\n",
    "                smart_version=data[\"smart_version\"],\n",
    "                specialty=specialty,\n",
    "                setting=setting,\n",
    "                created_at=datetime.now()\n",
    "            )\n",
    "            \n",
    "        except Exception as e:\n",
    "            logger.error(f\"Error generating SMART goal: {str(e)}\")\n",
    "            return None\n",
    "\n",
    "    async def _get_completion_stream(\n",
    "            self,\n",
    "            messages: List[Dict],\n",
    "            temperature: float = 0.7,\n",
    "            max_retries: int = 3\n",
    "        ) -> AsyncGenerator[str, None]:\n",
    "            \"\"\"\n",
    "            Get streaming completion from OpenRouter API with retry logic.\n",
    "            \n",
    "            Args:\n",
    "                messages: Conversation messages\n",
    "                temperature: Response temperature\n",
    "                max_retries: Maximum retry attempts\n",
    "                \n",
    "            Yields:\n",
    "                str: Response tokens as they arrive\n",
    "            \"\"\"\n",
    "            headers = {\n",
    "                \"Authorization\": f\"Bearer {self.api_key}\",\n",
    "                \"Content-Type\": \"application/json\",\n",
    "                \"HTTP-Referer\": \"http://localhost:7860\"\n",
    "            }\n",
    "            \n",
    "            data = {\n",
    "                \"model\": self.model,\n",
    "                \"messages\": messages,\n",
    "                \"temperature\": temperature,\n",
    "                \"max_tokens\": 2000,\n",
    "                \"stream\": True  # Enable streaming\n",
    "            }\n",
    "            \n",
    "            for attempt in range(max_retries):\n",
    "                try:\n",
    "                    async with aiohttp.ClientSession() as session:\n",
    "                        async with session.post(\n",
    "                            self.api_url,\n",
    "                            headers=headers,\n",
    "                            json=data,\n",
    "                            timeout=30\n",
    "                        ) as response:\n",
    "                            response.raise_for_status()\n",
    "                            \n",
    "                            # Process streaming response\n",
    "                            async for line in response.content:\n",
    "                                text = line.decode('utf-8').strip()\n",
    "                                if text.startswith('data: '):\n",
    "                                    try:\n",
    "                                        json_str = text[6:]  # Remove 'data: ' prefix\n",
    "                                        if json_str == '[DONE]':\n",
    "                                            break\n",
    "                                        \n",
    "                                        chunk = json.loads(json_str)\n",
    "                                        if token := chunk['choices'][0]['delta'].get('content'):\n",
    "                                            yield token\n",
    "                                            \n",
    "                                    except json.JSONDecodeError:\n",
    "                                        continue\n",
    "                                        \n",
    "                            return\n",
    "                            \n",
    "                except Exception as e:\n",
    "                    if attempt == max_retries - 1:\n",
    "                        raise OpenRouterException(f\"API call failed: {str(e)}\")\n",
    "                    logger.warning(f\"Retry {attempt + 1} after error: {str(e)}\")\n",
    "                    await asyncio.sleep(1 * (attempt + 1))  # Exponential backoff\n",
    "    \n",
    "    async def discuss_case(self, message: str) -> AsyncGenerator[str, None]:\n",
    "        \"\"\"\n",
    "        Process case discussion message with streaming response.\n",
    "        \n",
    "        Args:\n",
    "            message: User's message\n",
    "                \n",
    "        Yields:\n",
    "            str: Streamed tokens of tutor's response\n",
    "        \"\"\"\n",
    "        try:\n",
    "            # Build conversation prompt\n",
    "            system_prompt = self._build_discussion_prompt()\n",
    "            messages = [{\n",
    "                \"role\": \"system\",\n",
    "                \"content\": system_prompt\n",
    "            }, {\n",
    "                \"role\": \"user\",\n",
    "                \"content\": message\n",
    "            }]\n",
    "            \n",
    "            # Get streaming response\n",
    "            async for token in self._get_completion_stream(messages):\n",
    "                yield token\n",
    "                \n",
    "        except Exception as e:\n",
    "            logger.error(f\"Error in discussion: {str(e)}\")\n",
    "            yield \"I apologize, but I encountered an error. Please try again.\"\n",
    "            \n",
    "    def end_discussion(self) -> None:\n",
    "        \"\"\"End current discussion.\"\"\"\n",
    "        if self.learning_context.active_goal:\n",
    "            self.learning_context.complete_active_goal()\n",
    "            \n",
    "        self.current_discussion = []\n",
    "    \n",
    "    def _build_discussion_prompt(self) -> str:\n",
    "        \"\"\"Build context-aware discussion prompt.\"\"\"\n",
    "        context = self.learning_context\n",
    "        rotation = context.rotation\n",
    "        active_goal = context.active_goal\n",
    "        \n",
    "        return f\"\"\"You are an experienced clinical supervisor in {rotation.specialty} \n",
    "        working in a {rotation.setting} setting. Guide the learner through case discussion\n",
    "        using Socratic questioning and targeted feedback.\n",
    "\n",
    "        Current Learning Goal:\n",
    "        {active_goal.smart_version if active_goal else 'General clinical discussion'}\n",
    "\n",
    "        Approach:\n",
    "        1. Focus on clinical reasoning and decision-making\n",
    "        2. Ask targeted questions to explore understanding\n",
    "        3. Share relevant clinical pearls\n",
    "        4. Be conversational and engaging\n",
    "        5. Relate discussion to current learning goal where relevant\n",
    "\n",
    "        Remember: The learner has strong foundational knowledge. Focus on advanced clinical concepts\n",
    "        rather than basic science.\"\"\"\n",
    "                \n",
    "    def get_discussion_history(self) -> List[Dict]:\n",
    "        \"\"\"\n",
    "        Get current discussion history.\n",
    "        \n",
    "        Returns:\n",
    "            list: Discussion messages\n",
    "        \"\"\"\n",
    "        return self.current_discussion\n",
    "    \n",
    "    def clear_discussion() -> Tuple[List, str, Dict]:\n",
    "        \"\"\"Clear chat history.\"\"\"\n",
    "        return [], \"\", {\n",
    "            \"discussion_active\": False,\n",
    "            \"suggested_goals\": [],\n",
    "            \"discussion_start\": None,\n",
    "            \"last_message\": None\n",
    "        }\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75c2cbfc-75e7-45ee-9d86-b931f81a3ad5",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# old\n",
    "class ClinicalTutor:\n",
    "    \"\"\"\n",
    "    Adaptive clinical teaching module that provides context-aware feedback.\n",
    "    \n",
    "    The tutor acts as an experienced clinical supervisor, engaging in natural\n",
    "    case discussions while tracking student progress and adapting feedback\n",
    "    based on learning context.\n",
    "    \n",
    "    Attributes:\n",
    "        learning_context (LearningContext): Student's learning context\n",
    "        model (str): LLM model identifier\n",
    "        api_url (str): OpenRouter API endpoint\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(\n",
    "        self,\n",
    "        context_path: Optional[Path] = None,\n",
    "        model: str = \"anthropic/claude-3.5-sonnet\"\n",
    "    ):\n",
    "        \"\"\"\n",
    "        Initialize clinical tutor.\n",
    "        \n",
    "        Args:\n",
    "            context_path: Optional path for context persistence\n",
    "            model: Model identifier for OpenRouter\n",
    "        \"\"\"\n",
    "        self.api_key: str = os.getenv(\"OPENROUTER_API_KEY\")\n",
    "        if not self.api_key:\n",
    "            raise ValueError(\"OpenRouter API key not found\")\n",
    "        \n",
    "        self.api_url: str = \"https://openrouter.ai/api/v1/chat/completions\"\n",
    "        self.model: str = model\n",
    "        \n",
    "        self.learning_context = LearningContext(context_path)\n",
    "        self.context_path = context_path\n",
    "        \n",
    "        # Track conversation state\n",
    "        self.current_case: Dict = {\n",
    "            \"started\": None,\n",
    "            \"chief_complaint\": None,\n",
    "            \"key_findings\": [],\n",
    "            \"assessment\": None,\n",
    "            \"plan\": None\n",
    "        }\n",
    "        \n",
    "        logger.info(f\"Clinical tutor initialized with model: {model}\")\n",
    "    \n",
    "    async def _get_completion(\n",
    "        self,\n",
    "        messages: List[Dict],\n",
    "        temperature: float = 0.7,\n",
    "        max_retries: int = 3\n",
    "    ) -> str:\n",
    "        \"\"\"\n",
    "        Get completion from OpenRouter API with retry logic.\n",
    "        \n",
    "        Args:\n",
    "            messages: List of conversation messages\n",
    "            temperature: Temperature for response generation\n",
    "            max_retries: Maximum retry attempts\n",
    "            \n",
    "        Returns:\n",
    "            str: Model response\n",
    "            \n",
    "        Raises:\n",
    "            OpenRouterException: If API calls fail after retries\n",
    "        \"\"\"\n",
    "        headers = {\n",
    "            \"Authorization\": f\"Bearer {self.api_key}\",\n",
    "            \"Content-Type\": \"application/json\",\n",
    "            \"HTTP-Referer\": \"http://localhost:7860\"\n",
    "        }\n",
    "        \n",
    "        data = {\n",
    "            \"model\": self.model,\n",
    "            \"messages\": messages,\n",
    "            \"temperature\": temperature,\n",
    "            \"max_tokens\": 2000\n",
    "        }\n",
    "        \n",
    "        for attempt in range(max_retries):\n",
    "            try:\n",
    "                async with aiohttp.ClientSession() as session:\n",
    "                    async with session.post(\n",
    "                        self.api_url,\n",
    "                        headers=headers,\n",
    "                        json=data,\n",
    "                        timeout=30\n",
    "                    ) as response:\n",
    "                        response.raise_for_status()\n",
    "                        result = await response.json()\n",
    "                        return result[\"choices\"][0][\"message\"][\"content\"]\n",
    "                        \n",
    "            except Exception as e:\n",
    "                if attempt == max_retries - 1:\n",
    "                    raise OpenRouterException(f\"API call failed: {str(e)}\")\n",
    "                logger.warning(f\"Retry {attempt + 1} after error: {str(e)}\")\n",
    "                # Could add exponential backoff here if needed\n",
    "    \n",
    "    def _build_discussion_prompt(self) -> str:\n",
    "        \"\"\"Build context-aware prompt for case discussion.\"\"\"\n",
    "        rotation = self.learning_context.current_rotation\n",
    "        active_preferences = [\n",
    "            p[\"focus\"] for p in self.learning_context.feedback_preferences \n",
    "            if p[\"active\"]\n",
    "        ]\n",
    "        \n",
    "        significant_gaps = {\n",
    "            topic: score for topic, score \n",
    "            in self.learning_context.knowledge_profile[\"gaps\"].items()\n",
    "            if score < 0.7  # Only include significant gaps\n",
    "        }\n",
    "        \n",
    "        prompt = f\"\"\"You are an experienced clinical supervisor in {rotation['specialty']}. Act as an engaging and conversational tutor who coaches towards deeper understanding through Socratic dialogue and targeted questions.\n",
    "\n",
    "        Key Principles:\n",
    "        1. Assume I have strong foundational knowledge in medicine, clinical reasoning, and pre-medical sciences\n",
    "        2. Focus on high-level connections and nuanced clinical decision-making\n",
    "        3. Use targeted questions to explore my thought process and highlight key learning points\n",
    "        4. Share relevant clinical pearls and real-world applications\n",
    "        5. Be conversational and engaging, avoiding lecture-style responses\n",
    "        \n",
    "        Current Rotation Focus Areas:\n",
    "        {', '.join(rotation['key_focus_areas'])}\n",
    "\n",
    "        Areas for Deep Dive:\n",
    "        {', '.join(f'{topic} (confidence: {score:.1f})' for topic, score in significant_gaps.items()) if significant_gaps else 'General clinical reasoning'}\n",
    "\n",
    "        Student's Interests:\n",
    "        {', '.join(active_preferences) if active_preferences else 'Broad clinical discussion'}\n",
    "\n",
    "        Ask probing questions that explore clinical reasoning and highlight important connections. I will ask for clarification \n",
    "        if concepts need more explanation.\"\"\"\n",
    "\n",
    "        return prompt\n",
    "    \n",
    "    def _build_analysis_prompt(self, conversation: List[Dict[str, str]]) -> str:\n",
    "        \"\"\"\n",
    "        Build prompt for post-discussion analysis.\n",
    "        \n",
    "        Args:\n",
    "            conversation: List of message dictionaries with roles and content\n",
    "            \n",
    "        Returns:\n",
    "            str: Analysis prompt\n",
    "        \"\"\"\n",
    "        # Extract case details\n",
    "        case_content = \"\"\n",
    "        for msg in conversation:\n",
    "            if msg[\"role\"] == \"user\":\n",
    "                case_content += msg[\"content\"] + \"\\n\"\n",
    "        \n",
    "        return f\"\"\"Analyze the following case discussion between a medical student and \n",
    "        clinical supervisor. Focus on the student's demonstrated knowledge, skills, \n",
    "        and areas for improvement.\n",
    "\n",
    "        Case Content:\n",
    "        {case_content}\n",
    "\n",
    "        Please identify:\n",
    "        1. Key clinical concepts and learning points demonstrated or discussed\n",
    "        2. Areas where the student showed uncertainty or knowledge gaps\n",
    "        3. Strengths demonstrated in clinical reasoning and presentation\n",
    "        4. Specific learning objectives that would help the student's development\n",
    "\n",
    "        Frame your response to help with ongoing learning:\n",
    "        - Start with positive observations\n",
    "        - Be specific about knowledge gaps\n",
    "        - Make concrete suggestions for improvement\n",
    "        - Connect to practical clinical scenarios\"\"\"\n",
    "    \n",
    "    async def discuss_case(\n",
    "        self, \n",
    "        message: str,\n",
    "        temperature: float = 0.7\n",
    "    ) -> str:\n",
    "        \"\"\"\n",
    "        Natural case discussion with context-aware responses.\n",
    "        \n",
    "        Args:\n",
    "            message: Student's input message\n",
    "            temperature: Temperature for response generation\n",
    "            \n",
    "        Returns:\n",
    "            str: Clinical supervisor's response\n",
    "        \"\"\"\n",
    "        try:\n",
    "            # Update case tracking\n",
    "            if not self.current_case[\"started\"]:\n",
    "                self.current_case[\"started\"] = datetime.now()\n",
    "                # Try to identify chief complaint from first message\n",
    "                cc_match = re.search(r\"(\\d+)\\s*[yY][oO]\\s*[MmFf]\\s*with\\s*([^.]*)\", message)\n",
    "                if cc_match:\n",
    "                    self.current_case[\"chief_complaint\"] = cc_match.group(2).strip()\n",
    "            \n",
    "            # Build system prompt\n",
    "            system_prompt = self._build_discussion_prompt()\n",
    "            \n",
    "            messages = [{\n",
    "                \"role\": \"system\",\n",
    "                \"content\": system_prompt\n",
    "            }, {\n",
    "                \"role\": \"user\",\n",
    "                \"content\": message\n",
    "            }]\n",
    "            \n",
    "            response = await self._get_completion(messages, temperature)\n",
    "            return response\n",
    "            \n",
    "        except Exception as e:\n",
    "            logger.error(f\"Error in case discussion: {str(e)}\")\n",
    "            return \"I apologize, but I encountered an error. Please try presenting your case again.\"\n",
    "    \n",
    "    async def analyze_discussion(\n",
    "        self,\n",
    "        conversation: List[Dict[str, str]]\n",
    "    ) -> Dict[str, Any]:\n",
    "        \"\"\"\n",
    "        Analyze completed case discussion for learning insights.\n",
    "        \n",
    "        Args:\n",
    "            conversation: List of message dictionaries with roles and content\n",
    "            \n",
    "        Returns:\n",
    "            dict: Analysis results containing:\n",
    "                - learning_points: List of key concepts learned\n",
    "                - gaps: Dict of identified knowledge gaps\n",
    "                - strengths: List of demonstrated strengths\n",
    "                - suggested_objectives: List of recommended learning goals\n",
    "        \"\"\"\n",
    "        try:\n",
    "            # Reset case tracking\n",
    "            self.current_case = {\n",
    "                \"started\": None,\n",
    "                \"chief_complaint\": None,\n",
    "                \"key_findings\": [],\n",
    "                \"assessment\": None,\n",
    "                \"plan\": None\n",
    "            }\n",
    "            \n",
    "            # Get analysis from model\n",
    "            analysis_prompt = self._build_analysis_prompt(conversation)\n",
    "            messages = [{\n",
    "                \"role\": \"system\",\n",
    "                \"content\": analysis_prompt\n",
    "            }]\n",
    "            messages.extend(conversation)\n",
    "            \n",
    "            response = await self._get_completion(messages, temperature=0.3)\n",
    "            \n",
    "            # Parse insights\n",
    "            insights = self._parse_analysis(response)\n",
    "            \n",
    "            # Update learning context\n",
    "            self._update_context_from_analysis(insights)\n",
    "            \n",
    "            return insights\n",
    "            \n",
    "        except Exception as e:\n",
    "            logger.error(f\"Error in discussion analysis: {str(e)}\")\n",
    "            return {\n",
    "                \"learning_points\": [],\n",
    "                \"gaps\": {},\n",
    "                \"strengths\": [],\n",
    "                \"suggested_objectives\": []\n",
    "            }\n",
    "    \n",
    "    def _parse_analysis(self, response: str) -> Dict[str, Any]:\n",
    "        \"\"\"\n",
    "        Parse analysis response into structured insights.\n",
    "        \n",
    "        Uses pattern matching and basic NLP to extract:\n",
    "        - Learning points (key concepts discussed)\n",
    "        - Knowledge gaps with confidence estimates\n",
    "        - Demonstrated strengths\n",
    "        - Suggested learning objectives\n",
    "        \n",
    "        Args:\n",
    "            response: Raw analysis response\n",
    "            \n",
    "        Returns:\n",
    "            dict: Structured analysis insights\n",
    "        \"\"\"\n",
    "        insights = {\n",
    "            \"learning_points\": [],\n",
    "            \"gaps\": {},\n",
    "            \"strengths\": [],\n",
    "            \"suggested_objectives\": []\n",
    "        }\n",
    "        \n",
    "        try:\n",
    "            # Split into sections\n",
    "            sections = response.lower().split(\"\\n\\n\")\n",
    "            \n",
    "            for section in sections:\n",
    "                if \"learning point\" in section or \"key concept\" in section:\n",
    "                    # Extract bullet points or numbered items\n",
    "                    points = re.findall(r\"[-•*]\\s*(.+)$\", section, re.MULTILINE)\n",
    "                    insights[\"learning_points\"].extend(points)\n",
    "                    \n",
    "                elif \"gap\" in section or \"uncertainty\" in section:\n",
    "                    # Look for topic mentions with confidence indicators\n",
    "                    gaps = re.findall(\n",
    "                        r\"(limited|uncertain|unclear|difficulty with)\\s+([^,.]+)\", \n",
    "                        section\n",
    "                    )\n",
    "                    for indicator, topic in gaps:\n",
    "                        # Estimate confidence based on language\n",
    "                        confidence = 0.4 if \"limited\" in indicator else 0.6\n",
    "                        insights[\"gaps\"][topic.strip()] = confidence\n",
    "                        \n",
    "                elif \"strength\" in section or \"demonstrated\" in section:\n",
    "                    # Extract positive mentions\n",
    "                    strengths = re.findall(r\"[-•*]\\s*(.+)$\", section, re.MULTILINE)\n",
    "                    insights[\"strengths\"].extend(strengths)\n",
    "                    \n",
    "                elif \"objective\" in section or \"suggest\" in section:\n",
    "                    # Extract recommended objectives\n",
    "                    objectives = re.findall(r\"[-•*]\\s*(.+)$\", section, re.MULTILINE)\n",
    "                    insights[\"suggested_objectives\"].extend(objectives)\n",
    "            \n",
    "            return insights\n",
    "            \n",
    "        except Exception as e:\n",
    "            logger.error(f\"Error parsing analysis: {str(e)}\")\n",
    "            return insights\n",
    "    \n",
    "    def _update_context_from_analysis(self, insights: Dict[str, Any]) -> None:\n",
    "        \"\"\"\n",
    "        Update learning context based on discussion analysis.\n",
    "        \n",
    "        Args:\n",
    "            insights: Dictionary of analysis insights\n",
    "        \"\"\"\n",
    "        try:\n",
    "            # Update knowledge gaps\n",
    "            for topic, confidence in insights[\"gaps\"].items():\n",
    "                self.learning_context.update_knowledge_gap(topic, confidence)\n",
    "            \n",
    "            # Add strengths\n",
    "            for strength in insights[\"strengths\"]:\n",
    "                self.learning_context.add_strength(strength)\n",
    "            \n",
    "            # Save context if path provided\n",
    "            if self.context_path:\n",
    "                self.learning_context.save_context(self.context_path)\n",
    "                \n",
    "        except Exception as e:\n",
    "            logger.error(f\"Error updating context: {str(e)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6a2b15f5-6841-43cb-9b57-c0e3f1a0b0c2",
   "metadata": {},
   "source": [
    "## Tests"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67ee6bde-4ade-448e-a831-86f9f7ae82ea",
   "metadata": {},
   "outputs": [
    {
     "ename": "RuntimeError",
     "evalue": "asyncio.run() cannot be called from a running event loop",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mRuntimeError\u001b[0m                              Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[7], line 55\u001b[0m\n\u001b[0;32m     53\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;18m__name__\u001b[39m \u001b[38;5;241m==\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m__main__\u001b[39m\u001b[38;5;124m\"\u001b[39m:\n\u001b[0;32m     54\u001b[0m     \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01masyncio\u001b[39;00m\n\u001b[1;32m---> 55\u001b[0m     \u001b[43masyncio\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtest_clinical_tutor\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m\n",
      "File \u001b[1;32m~\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\asyncio\\runners.py:190\u001b[0m, in \u001b[0;36mrun\u001b[1;34m(main, debug, loop_factory)\u001b[0m\n\u001b[0;32m    161\u001b[0m \u001b[38;5;250m\u001b[39m\u001b[38;5;124;03m\"\"\"Execute the coroutine and return the result.\u001b[39;00m\n\u001b[0;32m    162\u001b[0m \n\u001b[0;32m    163\u001b[0m \u001b[38;5;124;03mThis function runs the passed coroutine, taking care of\u001b[39;00m\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    186\u001b[0m \u001b[38;5;124;03m    asyncio.run(main())\u001b[39;00m\n\u001b[0;32m    187\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m    188\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m events\u001b[38;5;241m.\u001b[39m_get_running_loop() \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m    189\u001b[0m     \u001b[38;5;66;03m# fail fast with short traceback\u001b[39;00m\n\u001b[1;32m--> 190\u001b[0m     \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mRuntimeError\u001b[39;00m(\n\u001b[0;32m    191\u001b[0m         \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124masyncio.run() cannot be called from a running event loop\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m    193\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m Runner(debug\u001b[38;5;241m=\u001b[39mdebug, loop_factory\u001b[38;5;241m=\u001b[39mloop_factory) \u001b[38;5;28;01mas\u001b[39;00m runner:\n\u001b[0;32m    194\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m runner\u001b[38;5;241m.\u001b[39mrun(main)\n",
      "\u001b[1;31mRuntimeError\u001b[0m: asyncio.run() cannot be called from a running event loop"
     ]
    }
   ],
   "source": [
    "#| hide\n",
    "\n",
    "from wardbuddy.clinical_tutor import ClinicalTutor\n",
    "from wardbuddy.learning_context import LearningCategory, SmartGoal\n",
    "\n",
    "async def test_clinical_tutor():\n",
    "    \"\"\"Test basic clinical tutor functionality.\"\"\"\n",
    "    # Setup test environment\n",
    "    if not os.getenv(\"OPENROUTER_API_KEY\"):\n",
    "        print(\"Skipping tests: No API key\")\n",
    "        return\n",
    "    \n",
    "    # Initialize tutor\n",
    "    tutor = ClinicalTutor()\n",
    "    \n",
    "    # Test case content\n",
    "    test_case = \"28yo M with chest pain, 2 days duration\"\n",
    "    \n",
    "    try:\n",
    "        # Test streaming discussion\n",
    "        full_response = \"\"\n",
    "        async for token in tutor.discuss_case(test_case):\n",
    "            full_response += token\n",
    "        \n",
    "        assert isinstance(full_response, str)\n",
    "        assert len(full_response) > 0\n",
    "        print(\"Discussion test passed\")\n",
    "        \n",
    "        # Test goal generation\n",
    "        goals = await tutor.generate_smart_goals(\"Emergency Medicine\", \"ED\")\n",
    "        assert isinstance(goals, list), \"Expected goals to be a list\"\n",
    "        assert len(goals) > 0, \"Expected at least one goal\"\n",
    "        assert all(isinstance(goal, SmartGoal) for goal in goals), \"Expected all items to be SmartGoal objects\"\n",
    "        print(\"Goal generation test passed\")\n",
    "        \n",
    "        # Test basic goal properties\n",
    "        test_goal = goals[0]\n",
    "        assert test_goal.specialty == \"Emergency Medicine\", \"Wrong specialty\"\n",
    "        assert test_goal.setting == \"ED\", \"Wrong setting\"\n",
    "        assert isinstance(test_goal.category, LearningCategory), \"Wrong category type\"\n",
    "        assert isinstance(test_goal.smart_version, str), \"Wrong goal text type\"\n",
    "        print(\"Goal properties test passed\")\n",
    "        \n",
    "        # Clear discussion\n",
    "        tutor.end_discussion()\n",
    "        assert len(tutor.get_discussion_history()) == 0, \"Discussion history not cleared\"\n",
    "        print(\"Discussion clearing test passed\")\n",
    "        \n",
    "        print(\"\\nAll tests passed! ✅\")\n",
    "        \n",
    "    except Exception as e:\n",
    "        print(f\"\\nTest failed ❌: {str(e)}\")\n",
    "        raise\n",
    "\n",
    "# Run tests\n",
    "if __name__ == \"__main__\":\n",
    "    try:\n",
    "        asyncio.run(test_clinical_tutor())\n",
    "    except RuntimeError:\n",
    "        # Handle case where event loop is already running\n",
    "        loop = asyncio.get_event_loop()\n",
    "        if loop.is_running():\n",
    "            loop.create_task(test_clinical_tutor())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3f469c37-afe3-4682-9cc4-40326ac21b74",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}