File size: 47,105 Bytes
0af0679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Welcome to the Second Lab - Exercise: Advanced Agentic Design Patterns\n",
    "\n",
    "This notebook extends the previous lab by adding the **Reflection Pattern** to improve response quality.\n",
    "\n",
    "### Patterns used in the original lab:\n",
    "1. **Multi-Model Comparison Pattern** - Comparing multiple models\n",
    "2. **Judge/Evaluator Pattern** - Evaluation by a judge model\n",
    "\n",
    "### New pattern added:\n",
    "3. **Reflection Pattern** - Self-improvement of responses"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table style=\"margin: 0; text-align: left; width:100%\">\n",
    "    <tr>\n",
    "        <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
    "            <img src=\"../assets/stop.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n",
    "        </td>\n",
    "        <td>\n",
    "            <h2 style=\"color:#ff7800;\">New Pattern: Reflection</h2>\n",
    "            <span style=\"color:#ff7800;\">The Reflection Pattern allows a model to critique and improve its own response. This is particularly useful for complex tasks requiring nuance and precision.</span>\n",
    "        </td>\n",
    "    </tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Start with imports - ask ChatGPT to explain any package that you don't know\n",
    "\n",
    "import os\n",
    "import json\n",
    "from dotenv import load_dotenv\n",
    "from openai import OpenAI\n",
    "from anthropic import Anthropic\n",
    "from IPython.display import Markdown, display\n",
    "\n",
    "# Always remember to do this!\n",
    "load_dotenv(override=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OpenAI API Key exists and begins sk-1kYcH\n",
      "Anthropic API Key exists and begins sk-ant-\n",
      "Google API Key not set (and this is optional)\n",
      "DeepSeek API Key not set (and this is optional)\n",
      "Groq API Key not set (and this is optional)\n"
     ]
    }
   ],
   "source": [
    "# Print the key prefixes to help with any debugging\n",
    "\n",
    "openai_api_key = os.getenv('OPENAI_API_KEY')\n",
    "anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n",
    "google_api_key = os.getenv('GOOGLE_API_KEY')\n",
    "deepseek_api_key = os.getenv('DEEPSEEK_API_KEY')\n",
    "groq_api_key = os.getenv('GROQ_API_KEY')\n",
    "\n",
    "if openai_api_key:\n",
    "    print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n",
    "else:\n",
    "    print(\"OpenAI API Key not set\")\n",
    "    \n",
    "if anthropic_api_key:\n",
    "    print(f\"Anthropic API Key exists and begins {anthropic_api_key[:7]}\")\n",
    "else:\n",
    "    print(\"Anthropic API Key not set (and this is optional)\")\n",
    "\n",
    "if google_api_key:\n",
    "    print(f\"Google API Key exists and begins {google_api_key[:2]}\")\n",
    "else:\n",
    "    print(\"Google API Key not set (and this is optional)\")\n",
    "\n",
    "if deepseek_api_key:\n",
    "    print(f\"DeepSeek API Key exists and begins {deepseek_api_key[:3]}\")\n",
    "else:\n",
    "    print(\"DeepSeek API Key not set (and this is optional)\")\n",
    "\n",
    "if groq_api_key:\n",
    "    print(f\"Groq API Key exists and begins {groq_api_key[:4]}\")\n",
    "else:\n",
    "    print(\"Groq API Key not set (and this is optional)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Generate Initial Question (Multi-Model Pattern)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated Question:\n",
      "A wealthy philanthropist has developed a new drug that can cure a rare but fatal disease affecting a small population. However, the drug is expensive to produce and the philanthropist only has enough resources to manufacture a limited supply. At the same time, a competing pharmaceutical company has discovered the cure but plans to charge exorbitant prices, making it inaccessible for most patients. \n",
      "\n",
      "The philanthropist learns that if they invest their resources into manufacturing the drug, it can be distributed at a lower cost but only to a select few who are already on a waiting list, prioritizing those who are most likely to recover. Alternatively, the philanthropist could sell the formula to the competing company for a substantial profit, ensuring that a broader population can access the cure, albeit at high prices that many cannot afford.\n",
      "\n",
      "The dilemma: Should the philanthropist prioritize the immediate health of a few individuals by providing the cure at a lower cost, or should they consider the greater good by allowing the competitive company to distribute the cure to a wider audience at a higher price?\n"
     ]
    }
   ],
   "source": [
    "# Generate a challenging question for the models to answer\n",
    "\n",
    "request = \"Please come up with a challenging ethical dilemma that requires careful moral reasoning and consideration of multiple perspectives. \"\n",
    "request += \"The dilemma should involve conflicting values and have no clear-cut answer. Answer only with the dilemma, no explanation.\"\n",
    "\n",
    "messages = [{\"role\": \"user\", \"content\": request}]\n",
    "\n",
    "openai = OpenAI()\n",
    "response = openai.chat.completions.create(\n",
    "    model=\"gpt-4o-mini\",\n",
    "    messages=messages,\n",
    ")\n",
    "\n",
    "question = response.choices[0].message.content\n",
    "print(\"Generated Question:\")\n",
    "print(question)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2: Get Initial Responses from Multiple Models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_initial_response(client, model_name, question, is_anthropic=False):\n",
    "    \"\"\"Get initial response from a model\"\"\"\n",
    "    messages = [{\"role\": \"user\", \"content\": question}]\n",
    "    \n",
    "    if is_anthropic:\n",
    "        response = client.messages.create(\n",
    "            model=model_name, \n",
    "            messages=messages, \n",
    "            max_tokens=1000\n",
    "        )\n",
    "        return response.content[0].text\n",
    "    else:\n",
    "        response = client.chat.completions.create(\n",
    "            model=model_name, \n",
    "            messages=messages\n",
    "        )\n",
    "        return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Configure clients\n",
    "openai_client = OpenAI()\n",
    "claude_client = Anthropic() if anthropic_api_key else None\n",
    "gemini_client = OpenAI(api_key=google_api_key, base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\") if google_api_key else None\n",
    "deepseek_client = OpenAI(api_key=deepseek_api_key, base_url=\"https://api.deepseek.com/v1\") if deepseek_api_key else None\n",
    "groq_client = OpenAI(api_key=groq_api_key, base_url=\"https://api.groq.com/openai/v1\") if groq_api_key else None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "=== INITIAL RESPONSES ===\n",
      "\n",
      "**gpt-4o-mini:**\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "This ethical dilemma presents a challenging decision for the philanthropist, who must weigh the immediate health needs of a few individuals against the broader societal implications of drug distribution and access.\n",
       "\n",
       "### Option 1: Prioritizing Immediate Health\n",
       "\n",
       "If the philanthropist chooses to manufacture the drug and distribute it at a lower cost to those on the waiting list, they are directly addressing the pressing health needs of a select few individuals who are already vulnerable. This action prioritizes compassion and the moral obligation to help those who are suffering. By ensuring that the drug is available to those with the highest likelihood of recovery, the philanthropist demonstrates an ethical commitment to saving lives and reducing suffering in the short term.\n",
       "\n",
       "However, this approach has limitations. By distributing the drug to only a small number of patients, the philanthropist may overlook other individuals who could benefit from the cure. Additionally, this solution does not address the systemic issue of access to healthcare and affordable medications for the larger population suffering from the disease.\n",
       "\n",
       "### Option 2: Considering the Greater Good\n",
       "\n",
       "On the other hand, selling the formula to the competing pharmaceutical company for a substantial profit could lead to a wider distribution of the drug, although at a higher price point that may make it inaccessible to many patients. In this scenario, the philanthropist uses their financial gain to potentially invest in other healthcare initiatives or research, thus contributing to the long-term improvement of medical care or addressing related health issues.\n",
       "\n",
       "This choice raises ethical concerns regarding the prioritization of profit over compassion and the risk that many individuals will remain unable to afford the life-saving treatment. It also creates a tension between the ideals of philanthropy and the realities of the pharmaceutical industry, which often operates on profit motives rather than altruistic goals.\n",
       "\n",
       "### Balancing the Two Options\n",
       "\n",
       "A possible compromise could be for the philanthropist to negotiate a deal with the pharmaceutical company that ensures a tiered pricing structure, where those who can afford the drug pay more while discounts or alternative funding are provided for low-income patients. This could help bridge the gap between immediate health needs and wider access.\n",
       "\n",
       "Ultimately, the decision comes down to the philanthropist's values and vision for their impact on public health. Do they prioritize saving a few lives in the short term or seek a more sustainable, albeit imperfect, solution that aims at broader access over a longer timeframe? The complexity of the dilemma emphasizes the need for thoughtful deliberation on how best to serve both individual health needs and the greater public good."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "==================================================\n",
      "\n",
      "**claude-3-7-sonnet-latest:**\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "# The Philanthropist's Dilemma\n",
       "\n",
       "This is a complex ethical dilemma that involves several important considerations:\n",
       "\n",
       "## Key Ethical Tensions\n",
       "\n",
       "- **Limited access at affordable prices** vs. **wider access at unaffordable prices**\n",
       "- **Immediate relief for a few** vs. **potential long-term access for many**\n",
       "- **Direct control over distribution** vs. **surrendering control to profit-motivated actors**\n",
       "\n",
       "## Considerations for Manufacturing the Drug Directly\n",
       "\n",
       "**Benefits:**\n",
       "- Ensures the most vulnerable patients receive treatment based on medical need rather than ability to pay\n",
       "- Maintains the philanthropist's ethical vision and control over distribution\n",
       "- Sets a precedent for compassionate drug pricing\n",
       "\n",
       "**Drawbacks:**\n",
       "- Limited overall reach due to resource constraints\n",
       "- Potentially slower scaling of production\n",
       "- Many patients may receive no treatment at all\n",
       "\n",
       "## Considerations for Selling to the Pharmaceutical Company\n",
       "\n",
       "**Benefits:**\n",
       "- Potentially greater production capacity and distribution reach\n",
       "- The philanthropist could use profits to subsidize costs for those who cannot afford it\n",
       "- Might accelerate further research and development\n",
       "\n",
       "**Drawbacks:**\n",
       "- Many patients would be excluded based on financial means\n",
       "- Surrenders control over an essential medicine to profit-motivated decision-making\n",
       "- Could establish a problematic precedent for pricing life-saving medications\n",
       "\n",
       "This dilemma reflects broader tensions in healthcare ethics between utilitarian approaches (helping the most people) and justice-based approaches (ensuring fair access based on need rather than wealth).\n",
       "\n",
       "There might be creative third options worth exploring, such as licensing agreements with price caps, creating a non-profit manufacturing entity, or partnering with governments to ensure broader affordable access."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "==================================================\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Collect initial responses\n",
    "initial_responses = {}\n",
    "competitors = []\n",
    "\n",
    "models = [\n",
    "    (\"gpt-4o-mini\", openai_client, False),\n",
    "    (\"claude-3-7-sonnet-latest\", claude_client, True),\n",
    "    (\"gemini-2.0-flash\", gemini_client, False),\n",
    "    (\"deepseek-chat\", deepseek_client, False),\n",
    "    (\"llama-3.3-70b-versatile\", groq_client, False),\n",
    "]\n",
    "\n",
    "print(\"\\n=== INITIAL RESPONSES ===\\n\")\n",
    "\n",
    "for model_name, client, is_anthropic in models:\n",
    "    if client:\n",
    "        try:\n",
    "            response = get_initial_response(client, model_name, question, is_anthropic)\n",
    "            initial_responses[model_name] = response\n",
    "            competitors.append(model_name)\n",
    "            \n",
    "            print(f\"**{model_name}:**\")\n",
    "            display(Markdown(response))\n",
    "            print(\"\\n\" + \"=\"*50 + \"\\n\")\n",
    "        except Exception as e:\n",
    "            print(f\"Error with {model_name}: {e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3: NEW PATTERN - Reflection Pattern"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def apply_reflection_pattern(client, model_name, original_question, initial_response, is_anthropic=False):\n",
    "    \"\"\"Apply the Reflection Pattern to improve a response\"\"\"\n",
    "    \n",
    "    reflection_prompt = f\"\"\"\n",
    "You previously received this question:\n",
    "{original_question}\n",
    "\n",
    "Here was your initial response:\n",
    "{initial_response}\n",
    "\n",
    "Now, as a critical expert, analyze your own response:\n",
    "1. What are the strengths of this response?\n",
    "2. What important perspectives are missing?\n",
    "3. Are there any biases or blind spots in the analysis?\n",
    "4. How could you improve this response?\n",
    "\n",
    "After this self-critique, provide an IMPROVED response that takes into account your observations.\n",
    "\n",
    "Response format:\n",
    "## Self-Critique\n",
    "[Your critical analysis of the initial response]\n",
    "\n",
    "## Improved Response\n",
    "[Your revised and improved response]\n",
    "\"\"\"\n",
    "    \n",
    "    messages = [{\"role\": \"user\", \"content\": reflection_prompt}]\n",
    "    \n",
    "    if is_anthropic:\n",
    "        response = client.messages.create(\n",
    "            model=model_name, \n",
    "            messages=messages, \n",
    "            max_tokens=1500\n",
    "        )\n",
    "        return response.content[0].text\n",
    "    else:\n",
    "        response = client.chat.completions.create(\n",
    "            model=model_name, \n",
    "            messages=messages\n",
    "        )\n",
    "        return response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "=== RESPONSES AFTER REFLECTION ===\n",
      "\n",
      "**gpt-4o-mini - After Reflection:**\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "## Self-Critique\n",
       "1. **Strengths of this Response:**\n",
       "   - The response thoroughly outlines both options available to the philanthropist, providing a balanced view of the ethical implications of each choice.\n",
       "   - It acknowledges the immediate health needs of affected individuals as well as the broader societal implications of drug distribution.\n",
       "   - It introduces a potential compromise solution, which adds depth to the analysis and suggests a more nuanced approach to the dilemma.\n",
       "\n",
       "2. **Important Perspectives Missing:**\n",
       "   - The response does not adequately consider the potential operational and logistical challenges in manufacturing and distributing the drug at a lower cost, including regulatory hurdles and the scalability of production.\n",
       "   - There is limited discussion on the emotional impact of the decision on the patients and their families, which could influence the philanthropist's considerations.\n",
       "   - The perspective of other stakeholders, such as healthcare providers and ethicists, is not introduced.\n",
       "\n",
       "3. **Biases or Blind Spots in the Analysis:**\n",
       "   - The response may lean towards prioritizing compassion over economic pragmatism, possibly downplaying the complexities involved in pharmaceutical economics and the realities that arise from selling to a corporation with profit motives.\n",
       "   - It assumes a binary choice rather than considering other stakeholder impacts and longer-term systemic solutions.\n",
       "\n",
       "4. **How to Improve This Response:**\n",
       "   - Include more contextual factors that might affect the decision, such as regulatory considerations, patient demographics, and healthcare infrastructure.\n",
       "   - Expand on the emotional and psychological aspects of the decision-making process for both the philanthropist and the patients involved.\n",
       "   - Address the potential for future societal implications if the competing company monopolizes the market after acquiring the formula.\n",
       "\n",
       "## Improved Response\n",
       "This ethical dilemma presents the philanthropist with a complex decision regarding how best to utilize limited resources to maximize the benefit for individuals suffering from a rare but fatal disease. The two primary options – providing a low-cost supply to a select few or selling the formula for broader but costly distribution – both highlight significant ethical considerations.\n",
       "\n",
       "### Option 1: Prioritizing Immediate Health\n",
       "By choosing to manufacture the drug at a lower cost for those on the waiting list, the philanthropist opts to directly address the urgent health needs of vulnerable individuals. This approach reflects a moral obligation to alleviate suffering and save lives in the short term. Prioritizing individuals with the highest likelihood of recovery can lead to tangible, immediate outcomes for those patients and their families.\n",
       "\n",
       "However, there are operational challenges associated with this choice. Limited production capabilities may mean that only a fraction of those in need can actually receive the drug, leaving many others without hope. Additionally, this decision doesn't resolve the systemic issues within healthcare, such as overall treatment accessibility and drug pricing, which may persist if not tackled holistically.\n",
       "\n",
       "### Option 2: Considering the Greater Good\n",
       "Alternatively, selling the formula to the competing pharmaceutical company could result in wider distribution of the drug and potentially more patients benefiting from the cure, albeit at higher prices. This choice could finance further philanthropic efforts or investments in healthcare that might ultimately lead to broader long-term improvements in public health.\n",
       "\n",
       "However, ethical concerns arise when considering the high pricing of the cure. The decision may disproportionately disadvantage lower-income patients, perpetuating healthcare inequities. Furthermore, there is the risk that this choice could enable the pharmaceutical company to monopolize treatment options, further exploitation in the industry.\n",
       "\n",
       "### A Balanced Approach\n",
       "To navigate this complex dilemma more thoughtfully, the philanthropist could explore a compromise by negotiating with the pharmaceutical company to establish a tiered pricing structure. This could create a system where the drug is offered at a reduced price for low-income patients, while ensuring sustainability for the company through higher prices for those who can afford them. Additionally, the philanthropist might advocate for a commitment from the company to invest in generics or alternative distribution methods to enhance accessibility.\n",
       "\n",
       "### Conclusion\n",
       "The choice ultimately hinges on the philanthropist's values and vision for their impact on public health. This decision requires careful consideration of immediate health benefits, long-term accessibility, and the emotional ramifications for affected individuals. By weighing the implications of each option and considering collaborative solutions, the philanthropist can work towards an outcome that promotes both individual care and broader societal well-being."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "==================================================\n",
      "\n",
      "**claude-3-7-sonnet-latest - After Reflection:**\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "## Self-Critique\n",
       "\n",
       "### Strengths of the initial response:\n",
       "- Well-structured analysis that clearly outlines the ethical tensions\n",
       "- Presents balanced considerations for both options\n",
       "- Mentions potential third options beyond the binary choice\n",
       "- Identifies the broader ethical frameworks at play (utilitarian vs. justice-based approaches)\n",
       "\n",
       "### Missing perspectives:\n",
       "1. **Stakeholder analysis**: The response lacks a thorough examination of all affected parties (patients, healthcare systems, future patients, etc.)\n",
       "2. **Timeline considerations**: No discussion of short-term vs. long-term consequences beyond immediate access\n",
       "3. **Public health impact**: Limited analysis of how each option affects overall public health outcomes\n",
       "4. **Precedent-setting effects**: Inadequate exploration of how this decision might influence future pharmaceutical development and pricing\n",
       "5. **Regulatory context**: No mention of potential government intervention, price controls, or other regulatory factors\n",
       "6. **Global justice perspective**: No consideration of how this decision affects different regions/countries\n",
       "\n",
       "### Biases and blind spots:\n",
       "1. **False dichotomy**: Despite mentioning \"third options,\" the analysis primarily treats this as a binary choice\n",
       "2. **Western/developed-world bias**: Assumes a market-based healthcare system without considering different global contexts\n",
       "3. **Individual-focused ethics**: Overemphasizes individual choice rather than institutional or systemic responsibilities\n",
       "4. **Overly abstract**: The analysis lacks concrete examples or case studies that might inform the decision\n",
       "5. **Neglect of power dynamics**: Doesn't address the power imbalance between corporations, individuals, and patients\n",
       "\n",
       "### Improvement opportunities:\n",
       "1. Provide a more nuanced spectrum of options beyond the binary choice\n",
       "2. Include more stakeholder perspectives, particularly patient voices\n",
       "3. Consider real-world case studies of similar pharmaceutical dilemmas\n",
       "4. Address systemic issues in drug development and pharmaceutical pricing\n",
       "5. Explore collaborative approaches that leverage multiple institutions\n",
       "6. Discuss intellectual property rights and their ethical implications\n",
       "\n",
       "## Improved Response\n",
       "\n",
       "# The Philanthropist's Dilemma: A Multidimensional Ethical Analysis\n",
       "\n",
       "This scenario presents not simply a binary choice but a complex ethical landscape involving multiple stakeholders, systemic factors, and competing values.\n",
       "\n",
       "## Stakeholder Analysis\n",
       "\n",
       "**Patients and families:**\n",
       "- Those currently suffering need immediate access regardless of mechanism\n",
       "- Future patients have interests in sustainable development of treatments\n",
       "- Economic diversity among patients means affordability affects different groups unequally\n",
       "\n",
       "**Healthcare systems:**\n",
       "- Must allocate limited resources across competing priorities\n",
       "- High-priced drugs can strain budgets and force difficult coverage decisions\n",
       "- Precedents set now affect future negotiations with pharmaceutical companies\n",
       "\n",
       "**Research community:**\n",
       "- Incentives for developing treatments for rare diseases are influenced by such cases\n",
       "- How intellectual property is handled affects future research priorities\n",
       "\n",
       "## Ethical Frameworks Worth Considering\n",
       "\n",
       "1. **Distributive justice**: Who should receive limited resources? What constitutes fair allocation?\n",
       "2. **Rights-based approach**: Do patients have a right to life-saving medication regardless of cost?\n",
       "3. **Consequentialist assessment**: Which option produces the best outcomes for the most people over time?\n",
       "4. **Virtue ethics**: What would a virtuous philanthropist do in this situation?\n",
       "5. **Global justice**: How does this decision affect healthcare equity across different regions?\n",
       "\n",
       "## Spectrum of Options\n",
       "\n",
       "Rather than two mutually exclusive choices, consider a spectrum of possibilities:\n",
       "\n",
       "1. **Direct manufacturing with tiered pricing**: Manufacture independently but implement income-based pricing to maximize access while maintaining sustainability\n",
       "\n",
       "2. **Conditional licensing**: License the formula with contractual price controls, distribution requirements, and accessibility guarantees\n",
       "\n",
       "3. **Public-private partnership**: Collaborate with governments, NGOs, and selected pharmaceutical partners to ensure broad, affordable access\n",
       "\n",
       "4. **Open-source approach**: Release the formula publicly with certain patent protections waived, while establishing a foundation to support manufacturing\n",
       "\n",
       "5. **Hybrid distribution model**: Manufacture for highest-need populations while licensing to reach others, using licensing revenues to subsidize direct manufacturing\n",
       "\n",
       "## Case Study Context\n",
       "\n",
       "Similar dilemmas have occurred with treatments for HIV/AIDS, hepatitis C, and rare genetic disorders. The outcomes suggest:\n",
       "\n",
       "- Maintaining some control over intellectual property while ensuring broad access often yields better public health outcomes than either extreme option\n",
       "- Patient advocacy can significantly influence corporate behavior and pricing\n",
       "- International differences in pricing and patent enforcement create complex dynamics\n",
       "- Government intervention through negotiation, compulsory licensing, or regulation often becomes necessary\n",
       "\n",
       "## Systems-Level Considerations\n",
       "\n",
       "This dilemma exists within broader systemic issues:\n",
       "\n",
       "- The current pharmaceutical development model creates inherent tensions between innovation, access, and affordability\n",
       "- Rare disease treatments highlight market failures in drug development\n",
       "- Healthcare financing systems vary globally, affecting how we should evaluate \"accessibility\"\n",
       "- Intellectual property regimes may require reform to better balance innovation incentives with public health needs\n",
       "\n",
       "## Recommended Approach\n",
       "\n",
       "The philanthropist should pursue a hybrid strategy that:\n",
       "\n",
       "1. Maintains sufficient control to ensure the most vulnerable patients receive treatment regardless of ability to pay\n",
       "\n",
       "2. Leverages partnerships with multiple entities (pharmaceutical companies, governments, NGOs) to maximize production scale and geographic reach\n",
       "\n",
       "3. Implements contractual safeguards on pricing, with particular attention to low and middle-income regions\n",
       "\n",
       "4. Establishes a patient assistance foundation using a portion of any licensing revenues\n",
       "\n",
       "5. Advocates for systemic reforms that would prevent such dilemmas in the future\n",
       "\n",
       "This approach recognizes that the philanthropist's responsibility extends beyond the immediate distribution decision to include consideration of precedent-setting effects, stakeholder equity, and systemic change—balancing immediate needs with long-term public health impact."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "==================================================\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Apply Reflection Pattern\n",
    "reflected_responses = {}\n",
    "\n",
    "print(\"\\n=== RESPONSES AFTER REFLECTION ===\\n\")\n",
    "\n",
    "for model_name, client, is_anthropic in models:\n",
    "    if client and model_name in initial_responses:\n",
    "        try:\n",
    "            reflected = apply_reflection_pattern(\n",
    "                client, model_name, question, \n",
    "                initial_responses[model_name], is_anthropic\n",
    "            )\n",
    "            reflected_responses[model_name] = reflected\n",
    "            \n",
    "            print(f\"**{model_name} - After Reflection:**\")\n",
    "            display(Markdown(reflected))\n",
    "            print(\"\\n\" + \"=\"*50 + \"\\n\")\n",
    "        except Exception as e:\n",
    "            print(f\"Error with reflection for {model_name}: {e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4: Comparative Evaluation (Extended Judge Pattern)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_comparative_evaluation(question, initial_responses, reflected_responses):\n",
    "    \"\"\"Create a comparative evaluation of responses before/after reflection\"\"\"\n",
    "    \n",
    "    evaluation_prompt = f\"\"\"\n",
    "You are evaluating the effectiveness of the \"Reflection Pattern\" on the following question:\n",
    "{question}\n",
    "\n",
    "For each model, you have:\n",
    "1. An initial response\n",
    "2. A response after self-reflection\n",
    "\n",
    "Analyze and compare:\n",
    "- Depth of analysis\n",
    "- Consideration of multiple perspectives\n",
    "- Nuance and sophistication of reasoning\n",
    "- Improvement brought by reflection\n",
    "\n",
    "MODELS TO EVALUATE:\n",
    "\"\"\"\n",
    "    \n",
    "    for model_name in initial_responses:\n",
    "        if model_name in reflected_responses:\n",
    "            evaluation_prompt += f\"\"\"\n",
    "## {model_name}\n",
    "\n",
    "### Initial response:\n",
    "{initial_responses[model_name][:500]}...\n",
    "\n",
    "### Response after reflection:\n",
    "{reflected_responses[model_name][:800]}...\n",
    "\n",
    "\"\"\"\n",
    "    \n",
    "    evaluation_prompt += \"\"\"\n",
    "Respond with structured JSON:\n",
    "{\n",
    "    \"general_analysis\": \"Your analysis of the Reflection Pattern's effectiveness\",\n",
    "    \"initial_ranking\": [\"best initially ranked model\", \"second\", \"third\"],\n",
    "    \"post_reflection_ranking\": [\"best ranked model after reflection\", \"second\", \"third\"],\n",
    "    \"most_improved\": \"Which model improved the most\",\n",
    "    \"insights\": \"Insights about the usefulness of the Reflection Pattern\"\n",
    "}\n",
    "\"\"\"\n",
    "    \n",
    "    return evaluation_prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "=== FINAL EVALUATION ===\n",
      "\n",
      "```json\n",
      "{\n",
      "    \"general_analysis\": \"The Reflection Pattern effectively enhanced the depth of analysis and consideration of multiple perspectives in both models. However, the results differ in terms of sophistication and detail. The GPT-4 model provided initial observations that were relatively shallow but improved by incorporating logistical challenges and suggesting compromises during reflection. In contrast, Claude-3's initial response was more structured and sophisticated, covering a broader range of ethical frameworks, but still showed room for improvement regarding stakeholder analysis and long-term impacts.\",\n",
      "    \"initial_ranking\": [\"claude-3-7-sonnet-latest\", \"gpt-4o-mini\"],\n",
      "    \"post_reflection_ranking\": [\"claude-3-7-sonnet-latest\", \"gpt-4o-mini\"],\n",
      "    \"most_improved\": \"gpt-4o-mini\",\n",
      "    \"insights\": \"The Reflection Pattern revealed significant gaps in both models' initial analyses, encouraging deeper engagement with ethical implications and stakeholder considerations. It highlighted the importance of reflecting on logistical realities and the real-world impacts of decisions, marking it as a worthwhile practice for ethical dilemmas.\"\n",
      "}\n",
      "```\n",
      "Could not parse JSON, raw output shown above\n"
     ]
    }
   ],
   "source": [
    "# Final evaluation\n",
    "if initial_responses and reflected_responses:\n",
    "    evaluation_prompt = create_comparative_evaluation(question, initial_responses, reflected_responses)\n",
    "    \n",
    "    judge_messages = [{\"role\": \"user\", \"content\": evaluation_prompt}]\n",
    "    \n",
    "    try:\n",
    "        judge_response = openai_client.chat.completions.create(\n",
    "            model=\"gpt-4o-mini\",\n",
    "            messages=judge_messages,\n",
    "        )\n",
    "        \n",
    "        evaluation_result = judge_response.choices[0].message.content\n",
    "        print(\"\\n=== FINAL EVALUATION ===\\n\")\n",
    "        print(evaluation_result)\n",
    "        \n",
    "        # Try to parse JSON for structured display\n",
    "        try:\n",
    "            eval_json = json.loads(evaluation_result)\n",
    "            print(\"\\n=== STRUCTURED RESULTS ===\\n\")\n",
    "            for key, value in eval_json.items():\n",
    "                print(f\"{key.replace('_', ' ').title()}: {value}\")\n",
    "        except:\n",
    "            print(\"Could not parse JSON, raw output shown above\")\n",
    "            \n",
    "    except Exception as e:\n",
    "        print(f\"Error during final evaluation: {e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simple Before/After Comparison"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "=== BEFORE vs AFTER COMPARISON ===\n",
      "\n",
      "\n",
      "==================== GPT-4O-MINI ====================\n",
      "\n",
      "BEFORE REFLECTION:\n",
      "--------------------------------------------------\n",
      "This ethical dilemma presents a challenging decision for the philanthropist, who must weigh the immediate health needs of a few individuals against the broader societal implications of drug distribution and access.\n",
      "\n",
      "### Option 1: Prioritizing Immediate Health\n",
      "\n",
      "If the philanthropist chooses to manufa...\n",
      "\n",
      "AFTER REFLECTION:\n",
      "--------------------------------------------------\n",
      "This ethical dilemma presents the philanthropist with a complex decision regarding how best to utilize limited resources to maximize the benefit for individuals suffering from a rare but fatal disease. The two primary options – providing a low-cost supply to a select few or selling the formula for broader but costly distribution – both highlight significant ethical considerations.\n",
      "\n",
      "### Option 1: P...\n",
      "\n",
      "======================================================================\n",
      "\n",
      "\n",
      "==================== CLAUDE-3-7-SONNET-LATEST ====================\n",
      "\n",
      "BEFORE REFLECTION:\n",
      "--------------------------------------------------\n",
      "# The Philanthropist's Dilemma\n",
      "\n",
      "This is a complex ethical dilemma that involves several important considerations:\n",
      "\n",
      "## Key Ethical Tensions\n",
      "\n",
      "- **Limited access at affordable prices** vs. **wider access at unaffordable prices**\n",
      "- **Immediate relief for a few** vs. **potential long-term access for many...\n",
      "\n",
      "AFTER REFLECTION:\n",
      "--------------------------------------------------\n",
      "# The Philanthropist's Dilemma: A Multidimensional Ethical Analysis\n",
      "\n",
      "This scenario presents not simply a binary choice but a complex ethical landscape involving multiple stakeholders, systemic factors, and competing values.\n",
      "\n",
      "## Stakeholder Analysis\n",
      "\n",
      "**Patients and families:**\n",
      "- Those currently suffering need immediate access regardless of mechanism\n",
      "- Future patients have interests in sustainable d...\n",
      "\n",
      "======================================================================\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Display side-by-side comparison for each model\n",
    "print(\"\\n=== BEFORE vs AFTER COMPARISON ===\\n\")\n",
    "\n",
    "for model_name in initial_responses:\n",
    "    if model_name in reflected_responses:\n",
    "        print(f\"\\n{'='*20} {model_name.upper()} {'='*20}\\n\")\n",
    "        \n",
    "        print(\"BEFORE REFLECTION:\")\n",
    "        print(\"-\" * 50)\n",
    "        print(initial_responses[model_name][:300] + \"...\")\n",
    "        \n",
    "        print(\"\\nAFTER REFLECTION:\")\n",
    "        print(\"-\" * 50)\n",
    "        # Extract just the \"Improved Response\" section if it exists\n",
    "        reflected = reflected_responses[model_name]\n",
    "        if \"## Improved Response\" in reflected:\n",
    "            improved_section = reflected.split(\"## Improved Response\")[1].strip()\n",
    "            print(improved_section[:400] + \"...\")\n",
    "        else:\n",
    "            print(reflected[:400] + \"...\")\n",
    "        \n",
    "        print(\"\\n\" + \"=\"*70 + \"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table style=\"margin: 0; text-align: left; width:100%\">\n",
    "    <tr>\n",
    "        <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
    "            <img src=\"../assets/exercise.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n",
    "        </td>\n",
    "        <td>\n",
    "            <h2 style=\"color:#ff7800;\">Pattern Analysis</h2>\n",
    "            <span style=\"color:#ff7800;\">\n",
    "            <b>Patterns used:</b><br/>\n",
    "            1. <b>Multi-Model Comparison:</b> Comparing multiple models on the same task<br/>\n",
    "            2. <b>Judge/Evaluator:</b> Using a model to evaluate performances<br/>\n",
    "            3. <b>Reflection (NEW):</b> Self-critique and improvement of responses<br/><br/>\n",
    "            <b>Possible experiments:</b><br/>\n",
    "            - Iterate the Reflection Pattern multiple times<br/>\n",
    "            - Add a \"Debate Pattern\" between models<br/>\n",
    "            - Implement a \"Consensus Pattern\"\n",
    "            </span>\n",
    "        </td>\n",
    "    </tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<table style=\"margin: 0; text-align: left; width:100%\">\n",
    "    <tr>\n",
    "        <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
    "            <img src=\"../assets/business.png\" width=\"150\" height=\"150\" style=\"display: block;\" />\n",
    "        </td>\n",
    "        <td>\n",
    "            <h2 style=\"color:#00bfff;\">Commercial Applications</h2>\n",
    "            <span style=\"color:#00bfff;\">\n",
    "            The <b>Reflection Pattern</b> is particularly valuable for:<br/>\n",
    "            • Improving quality of complex analyses<br/>\n",
    "            • Reducing bias in AI recommendations<br/>\n",
    "            • Creating self-improving systems<br/>\n",
    "            • Developing more robust AI for critical decisions<br/><br/>\n",
    "            Use cases: Strategic consulting, risk analysis, ethical evaluation, medical diagnosis\n",
    "            </span>\n",
    "        </td>\n",
    "    </tr>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Additional Pattern Ideas for Future Implementation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Exercise completed! Analyze the results to see the impact of the Reflection Pattern.\n"
     ]
    }
   ],
   "source": [
    "# 1. Chain of Thought Pattern\n",
    "\"\"\"\n",
    "Add a pattern that asks models to show their reasoning step by step:\n",
    "\n",
    "def apply_chain_of_thought_pattern(client, question):\n",
    "    prompt = f\\\"\n",
    "    Question: {question}\n",
    "    \n",
    "    Please think through this step by step:\n",
    "    Step 1: [Identify the key issues]\n",
    "    Step 2: [Consider different perspectives]\n",
    "    Step 3: [Evaluate potential consequences]\n",
    "    Step 4: [Provide reasoned conclusion]\n",
    "    \\\"\n",
    "    return get_response(client, prompt)\n",
    "\"\"\"\n",
    "\n",
    "# 2. Iterative Refinement Pattern\n",
    "\"\"\"\n",
    "Create a loop that progressively improves the response over multiple iterations:\n",
    "\n",
    "def iterative_refinement(client, question, iterations=3):\n",
    "    response = get_initial_response(client, question)\n",
    "    for i in range(iterations):\n",
    "        critique_prompt = f\\\"Improve this response: {response}\\\"\n",
    "        response = get_response(client, critique_prompt)\n",
    "    return response\n",
    "\"\"\"\n",
    "\n",
    "# 3. Debate Pattern\n",
    "\"\"\"\n",
    "Make two models debate their respective responses:\n",
    "\n",
    "def create_debate(client1, client2, question):\n",
    "    response1 = get_response(client1, question)\n",
    "    response2 = get_response(client2, question)\n",
    "    \n",
    "    debate_prompt1 = f\\\"Argue against this position: {response2}\\\"\n",
    "    debate_prompt2 = f\\\"Argue against this position: {response1}\\\"\n",
    "    \n",
    "    counter1 = get_response(client1, debate_prompt1)\n",
    "    counter2 = get_response(client2, debate_prompt2)\n",
    "    \n",
    "    return counter1, counter2\n",
    "\"\"\"\n",
    "\n",
    "# 4. Consensus Building Pattern\n",
    "\"\"\"\n",
    "Attempt to create a consensus response based on all individual responses:\n",
    "\n",
    "def build_consensus(all_responses, question):\n",
    "    consensus_prompt = f\\\"\n",
    "    Original question: {question}\n",
    "    \n",
    "    Here are multiple expert responses:\n",
    "    {all_responses}\n",
    "    \n",
    "    Create a consensus response that incorporates the best insights from all responses\n",
    "    while resolving contradictions.\n",
    "    \\\"\n",
    "    return get_response(openai_client, consensus_prompt)\n",
    "\"\"\"\n",
    "\n",
    "print(\"Exercise completed! Analyze the results to see the impact of the Reflection Pattern.\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}