File size: 41,277 Bytes
4fd4ce2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "UwPf_0rc4KZJ"
   },
   "source": [
    "# Notebook which Uses 3 Agents to Come to a Conclusion for a Query Regarding 2 Countries\n",
    "\n",
    "This is just an experimental notebook to explore interacting agents for the above purpose, not implemented in Streamlit app for reasons below,.\n",
    "\n",
    "Idea: 3 agents will be used, the first 2 agents will be ESG policy experts for each of the 2 countries that the user selects, they contribute to the conversation by using their RetrievalQA tools to find out the relevant ESG policy for their own countries. The 3rd agent will be the moderator without access to any tool which ideally uses the first 2 agent's input to come to a conclusion about the user query/topic of interest.\n",
    "\n",
    "Result: However this doesn't work very well, each of the agents tend to continue to simulate the conversation for other parties after giving their own input, despite being prompted not to do so. The moderator also tends to hallucinate no matter which temperature isused. For now, too many things can go wrong in the middle of the conversation between the 2 agents, and too many prompts are needed to try to get everything right.\n",
    "\n",
    "But in this case, even with the current free LLM API, it is clear from the second notebook that a single agent has the ability to reason all the steps out to answer a query regarding 2 countries. Hence the previous notebook of having a single agent equipped with the RetrievalQA tool is used eventually in the app.\n",
    "\n",
    "Maybe multiple agents like these can be used for a debate between ESG policies instead, where each agent tries to convince the other of its views."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from langchain.llms import HuggingFaceHub # for calling HuggingFace Inference API (free for our use case)\n",
    "from langchain.embeddings import HuggingFaceEmbeddings # to let program know what embeddings the vector store was embedded in earlier\n",
    "\n",
    "# to set up the agent and tools which will be used to answer questions later\n",
    "from langchain.agents import initialize_agent \n",
    "from langchain.agents import tool # decorator so each function will be recognized as a tool\n",
    "from langchain.chains.retrieval_qa.base import RetrievalQA # to answer questions from vector store retriever\n",
    "# from langchain.chains.question_answering import load_qa_chain # to further customize qa chain if needed\n",
    "from langchain.vectorstores import Chroma # vector store for retriever\n",
    "import ast # to parse user string input to list for one of the tools (agent tools do not support 2 inputs)\n",
    "#from langchain.memory import ConversationBufferMemory # not used as of now\n",
    "import pickle # for loading the bm25 retriever\n",
    "from langchain.retrievers import EnsembleRetriever # to use chroma and \n",
    "\n",
    "# for defining a generic LLMChain as a generic chat tool (if needed)\n",
    "from langchain.prompts import PromptTemplate \n",
    "from langchain.chains import LLMChain\n",
    "\n",
    "from langchain.schema import (AIMessage, HumanMessage, SystemMessage,) # for dialogue agent messages\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\", category=FutureWarning)\n",
    "warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n",
    "\n",
    "# os.environ['HUGGINGFACEHUB_API_TOKEN'] = 'your_api_key' # for using HuggingFace Inference API\n",
    "# alternatively set your env variable above"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "id": "JxAiGlN74KZM"
   },
   "outputs": [],
   "source": [
    "from typing import Callable, List\n",
    "\n",
    "from langchain.memory import ConversationBufferMemory"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9dJtw15E4KZN"
   },
   "source": [
    "# Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "skvoIwYU4KZO"
   },
   "outputs": [],
   "source": [
    "chunk_size = 1000 # choose one of [500, 600, 700, 800, 900, 1000, 1250, 1500, 1750, 2000, 2250, 2500, 2750, 3000]\n",
    "chunk_overlap = 100 # choose one of [50, 100, 150, 200]\n",
    "\n",
    "chroma_n_similar_documents = 6 # number of chunks returned by chroma vector store retriever\n",
    "bm25_n_similar_documents = 6 # number of chunks returned by bm25 retriever\n",
    "\n",
    "# llm for HuggingFace Inference API\n",
    "# model = \"mistralai/Mistral-7B-Instruct-v0.2\"\n",
    "model = \"mistralai/Mixtral-8x7B-Instruct-v0.1\"\n",
    "\n",
    "# what retrievers to use, if ensemble is chosen then both semantic and keyword similarity documents will be used and results reranked\n",
    "retriever_config = 'ensemble' # choose one of ['semantic', 'keyword', 'ensemble'] # ensemble means both\n",
    "keyword_retriever_weight = 0.3 # choose between 0 and 1\n",
    "semantic_retriever_weight = 1 - keyword_retriever_weight\n",
    "\n",
    "# llm configuration\n",
    "temperature = 0.1\n",
    "max_new_tokens = 500\n",
    "\n",
    "# in main app, add configuration for user to scrape new data from DuckDuckGo\n",
    "# in main app, add configuration for user to upload PDF to override country's existing policies in vectorstore"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conversation Topic\n",
    "\n",
    "Ideally this will be changed when user asks a query to match the query."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "topic = \"Compare the carbon emissions policies between Singapore and Malaysia.\"\n",
    "countries_in_query = ['Singapore', 'Malaysia']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Countries of Interest\n",
    "\n",
    "- This is the list of countries present in the vectore store, since the vector store is prepared from the previous Scrape_Web_and_Process_Data_for_Countries_ESG_Policies notebook, it should be the same list of countries in that notebook.  \n",
    "- This is for coding the RetrievalQA tool later to check, because even if the country given to it is not in the vector store, it would still filter the vector store with this country and give an empty result, instead of giving an error. We have to manually return the error to let the agent using the tool know.\n",
    "- The countries were reduced to just 6 as the time taken to get the embeddings to build up the chunks is too long. However, having more countries **will not affect** the quality of the answers in comparing between 2 countries in the RAG application as the RAG only picks out document chunks for the 2 countries of interest.\n",
    "\n",
    "- In the main app, user can choose which countries to scrape data for, and this list would be adjusted accordingly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "countries = [\n",
    "    \"Australia\",\n",
    "    \"China\",\n",
    "    \"Japan\",\n",
    "    \"Malaysia\",\n",
    "    \"Singapore\",\n",
    "    \"Germany\",\n",
    "    ]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# LLM from HuggingFace Inference Endpoint API"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# This is an inference endpoint API from huggingface, the model is not run locally, it is run on huggingface\n",
    "# It is a free API that is very good for deploying online for quick testing without users having to deploy a local LLM\n",
    "llm = HuggingFaceHub(repo_id=model,model_kwargs={'temperature':temperature,\"max_new_tokens\":max_new_tokens})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Initialize Chroma Vector Store\n",
    "\n",
    "As per the Scrape_Web_and_Process_Data_for_Countries_ESG_Policies notebook. Chromadb vector stores have **already been pre-created** for the countries above for each of the different chunk sizes and overlaps, to save time when experimenting as the embeddings take a long time to generate. When using the existing vector stores, we just need to change the name of the persist directory when selecting the different chunk sizes and overlaps.\n",
    "\n",
    "Not in this notebook: Later in the main app if the **user choose to scrape new data, or override with their own PDF, a new chromadb directory would be created** and the chroma_db parameter would be changed accordingly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "D:\\Machine Learning Projects\\m\\llm\\venv\\lib\\site-packages\\transformers\\utils\\generic.py:311: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
      "  torch.utils._pytree._register_pytree_node(\n"
     ]
    }
   ],
   "source": [
    "# We use HuggingFaceEmbeddings() as it is open source and free to use.\n",
    "# Initialize the default hf model for embedding the tokenized texts into vectors with semantic meanings\n",
    "hf_embeddings = HuggingFaceEmbeddings()\n",
    "persist_directory = f\"chromadb/chromadb_esg_countries_chunk_{chunk_size}_overlap_{chunk_overlap}\"\n",
    "\n",
    "# in main app this chroma_db\n",
    "chroma_db = Chroma(persist_directory=persist_directory,embedding_function=hf_embeddings)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Initialize BM25 Retriever\n",
    "\n",
    "- BM25 is a keyword-based algorithm that performs well on queries containing keywords without capturing the semantic meaning of the query terms, hence there is no need to embed the text with HuggingFaceEmbeddings and it is relatively faster to set up. The retrievers with different chunking sizes and overlaps and countries are saved as pickle files in the earlier notebook.\n",
    "\n",
    "- Need to initialize one BM25Retriever for each country so the search results later in the main app can be limited to just a particular country. (Chroma DB gives an option to filter metadata for just a particular country during the retrieval processbut BM25 does not because it makes use of external ranking library.) A separate retriever was saved for each country in the earlier notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "bm25_retrievers = {}\n",
    "\n",
    "for country in countries:\n",
    "    bm25_filename = f\"bm25/bm25_esg_countries_{country}_chunk_{chunk_size}_overlap_{chunk_overlap}.pickle\"\n",
    "    with open(bm25_filename, 'rb') as handle:\n",
    "        bm25_retriever = pickle.load(handle)    \n",
    "        bm25_retriever.k = bm25_n_similar_documents\n",
    "        bm25_retrievers[country] = bm25_retriever"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Potential Tools for LLM Agent to Use\n",
    "\n",
    "Please see comments above each tool. The first tool is the most important one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The most important tool is the first one, which uses a RetrievalQA chain to answer a question about a specific country's ESG policies, \n",
    "# e.g. carbon emissions policy of Singapore. \n",
    "# By calling this tool multiple times, the agent is able to look at the responses from this tool for both countries and compare them. \n",
    "# This is far better than just retrieving relevant chunks for the user's query and throw everything to a single RetrievalQA chain to process\n",
    "# Multi input tools are not available, hence we have to prompt the agent to give an input list as a string\n",
    "# then use ast.literal_eval to convert it back into a list\n",
    "@tool \n",
    "def retrieve_answer_for_country(query_and_country: str) -> str: # TODO, change diff chain type diff version answers, change \n",
    "    \"\"\"Gives answer to a query about a single country's public ESG policy.\n",
    "    The input list should be of the following format:\n",
    "    [country, query]\n",
    "    The first element of the list is the user query, surrounded by double quotes.\n",
    "    The second element is the full name of the country involved, surrounded by double quotes, for example \"Singapore\".\n",
    "    The 2 inputs are separated by a comma. Do not write a list comprehension.\n",
    "    The 2 inputs, together, are surrounded by square brackets as it is a list.\n",
    "    Do not put multiple countries into the input at once. Instead use this tool multiple times, one time for each country.\n",
    "    If you have multiple queries to ask about a country, break the query into separate parts and use this tool multiple times, one for each query.\n",
    "    \"\"\"\n",
    "    try:\n",
    "        query_and_country_list = ast.literal_eval(query_and_country)\n",
    "        query = query_and_country_list[0]\n",
    "        country = query_and_country_list[1].capitalize() # in case LLM did not capitalize first letter as filtering for metadata is case sensitive\n",
    "        if not country in countries:\n",
    "            return \"\"\"The country that you input into the tool cannot be found. \n",
    "            If you did not make a mistake and the country that you input is indeed what the user asked,\n",
    "            then there is no record for the country and no answer can be obtained.\"\"\"\n",
    "\n",
    "        # different retrievers\n",
    "        bm = bm25_retrievers[country] # keyword based\n",
    "        bm.k = bm25_n_similar_documents \n",
    "        chroma = chroma_db.as_retriever(search_kwargs={'filter': {'country':country}, 'k': chroma_n_similar_documents}) # semantic\n",
    "        ensemble = EnsembleRetriever(retrievers=[bm, chroma], weights=[keyword_retriever_weight, semantic_retriever_weight]) # ensemble reranks results from both retrievers\n",
    "        retrievers = {'ensemble': ensemble, 'semantic': chroma, 'keyword': bm}      \n",
    "        \n",
    "        qa = RetrievalQA.from_chain_type(\n",
    "            llm=llm,\n",
    "            chain_type='stuff',\n",
    "            retriever=retrievers[retriever_config], # selected retriever based on user config\n",
    "        )\n",
    "        result = qa.run(query)\n",
    "        return result\n",
    "    except Exception as e:\n",
    "        return f\"\"\"There is an error using this tool: {e}. Check if you have input anything wrongly and try again. \n",
    "        If you have already tried 2 times, do not try anymore, there is no answer for your input. \n",
    "        Move on to the next step of your plan.\"\"\"\n",
    "\n",
    "# if a user tries to casually chat with the agent chatbot, the LLM will be able to use this tool to reply instead\n",
    "# this is optional, better to let user's know the chatbot is not for casual chatting\n",
    "@tool\n",
    "def generic_chat_llm(query: str) -> str:\n",
    "    \"\"\"Use this tool for general queries and casual chat. Forward the user input directly into this tool, do not come up with your own input.\n",
    "    This tool IS NOT FOR MAKING COMPARISONS of anything.\n",
    "    This tool IS NOT FOR FINDING ESG POLICY of any country!\n",
    "    It is only for casual chat! Do not use this tool unnecessarily!\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # Second Generic Tool\n",
    "        prompt = PromptTemplate(\n",
    "            input_variables=[\"query\"],\n",
    "            template=\"{query}\"\n",
    "        )\n",
    "    \n",
    "        llm_chain = LLMChain(llm=llm, prompt=prompt)\n",
    "        return llm_chain.run(query)\n",
    "\n",
    "    except Exception as e:\n",
    "        return f\"\"\"There is an error using this tool: {e}. Check if you have input anything wrongly and try again. \n",
    "        If you have already tried 2 times, do not try anymore, there is no response for your input.\n",
    "        Move on to the next step of your plan.\"\"\"\n",
    "\n",
    "# sometimes the agent will suddenly ask for a 'compare' tool even though it was not given this tool\n",
    "# hence I have decided to give it this tool that gives a prompt to remind it to look at past information\n",
    "# and decide whether it is time to darw a conclusion\n",
    "# tools cannot have no input, hence I let the agent input a 'query' parameter even though it is not used\n",
    "# having the query as input let the LLM 'recall' what is being asked \n",
    "# instead of it being lost all the way at the start of the ReAct process\n",
    "# this is optional\n",
    "@tool\n",
    "def compare(query:str) -> str: \n",
    "    \"\"\"Use this tool to give you hints and instructions on how you can compare between policies of countries.\n",
    "    Use this tool only at one of your final steps, do not use it at the start.\n",
    "    When putting the query into this tool, look at the entire query that the user has asked at the start,\n",
    "    do not leave any details in the query out.\n",
    "    \"\"\"\n",
    "    return f\"\"\"Once again, check through all your previous observations to answer the user query. \n",
    "    Make sure every part of the query is addressed by the context, or that you have at least tried to do so.\n",
    "    Make sure you have not forgotten to address anything in the query.\n",
    "    If you still need more details, you can use another tool to find out more if you have not tried using the same tool with the necessary input earlier. \n",
    "    If you have enough information, use your reasoning to answer them to the best of your ability. \n",
    "    Give as much elaboration in your answer as possible but they MUST be from the earlier context.\n",
    "    Do not give details that cannot be found in the earlier context.\"\"\"\n",
    "\n",
    "\n",
    "tools = [retrieve_answer_for_country] # tools that the dialogueAgentWithTools below will use"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bIRlTdk84KZO"
   },
   "source": [
    "## DialogueAgent, DialogueSimulator and DialogueAgentWithTools classes\n",
    "\n",
    "These are agents which will speak to one another. These are adapted from the Langchain cookbook [Multi-Player Authoritarian Speaker Selection](https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html).\n",
    "\n",
    "The DialogueAgent class has 2 main methods:\r\n",
    "\r\n",
    "- send(): applies the chatmodel to the message history and returns the message string generated by LLM.\r\n",
    "- receive(name, message): adds the message spoken by name to message hist.ory\r\n",
    "\r\n",
    "\r\n",
    "The DialogueSimulator class takes a list of agents. At each step, it performs the following:\r\n",
    "\r\n",
    "- Select he next. speaker\r\n",
    "- Calls the next speaker to send .a message\r\n",
    "- Broadcasts the message to all ot.her agents\r\n",
    "- Update the strough the a the aagents.toryory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "id": "wl-goiWJ4KZO"
   },
   "outputs": [],
   "source": [
    "class DialogueAgent:\n",
    "    def __init__(\n",
    "        self,\n",
    "        name: str,\n",
    "        system_message: SystemMessage,\n",
    "        model: llm,\n",
    "    ) -> None:\n",
    "        self.name = name\n",
    "        self.system_message = system_message\n",
    "        self.model = model\n",
    "        self.prefix = f\"{self.name}: \"\n",
    "        self.reset()\n",
    "\n",
    "    def reset(self):\n",
    "        self.message_history = [\"Here is the conversation so far.\"]\n",
    "\n",
    "    def send(self) -> str:\n",
    "        \"\"\"\n",
    "        Applies the chatmodel to the message history\n",
    "        and returns the message string\n",
    "        \"\"\"\n",
    "        message = self.model(\n",
    "                \"\\n\".join([self.system_message.content] + self.message_history + [self.prefix]))\n",
    "        return message\n",
    "\n",
    "    def receive(self, name: str, message: str) -> None:\n",
    "        \"\"\"\n",
    "        Concatenates {message} spoken by {name} into message history\n",
    "        \"\"\"\n",
    "        self.message_history.append(f\"{name}: {message}\")\n",
    "\n",
    "\n",
    "class DialogueSimulator:\n",
    "    def __init__(\n",
    "        self,\n",
    "        agents: List[DialogueAgent],\n",
    "        selection_function: Callable[[int, List[DialogueAgent]], int],\n",
    "    ) -> None:\n",
    "        self.agents = agents\n",
    "        self._step = 0\n",
    "        self.select_next_speaker = selection_function\n",
    "\n",
    "    def reset(self):\n",
    "        for agent in self.agents:\n",
    "            agent.reset()\n",
    "\n",
    "    def inject(self, name: str, message: str):\n",
    "        \"\"\"\n",
    "        Initiates the conversation with a {message} from {name}\n",
    "        \"\"\"\n",
    "        for agent in self.agents:\n",
    "            agent.receive(name, message)\n",
    "\n",
    "        # increment time\n",
    "        self._step += 1\n",
    "\n",
    "    def step(self) -> tuple[str, str]:\n",
    "        # 1. choose the next speaker\n",
    "        speaker_idx = self.select_next_speaker(self._step, self.agents)\n",
    "        speaker = self.agents[speaker_idx]\n",
    "        print(f\"\\n\\n############ {speaker.name} is thinking.....\")\n",
    "\n",
    "        # 2. next speaker sends message\n",
    "        message = speaker.send()\n",
    "\n",
    "        # 3. everyone receives message\n",
    "        for receiver in self.agents:\n",
    "            receiver.receive(speaker.name, message)\n",
    "\n",
    "        # 4. increment time\n",
    "        self._step += 1\n",
    "\n",
    "        return speaker.name, message\n",
    "\n",
    "\n",
    "class DialogueAgentWithTools(DialogueAgent): # inherit from DialogueAgent class but with tools\n",
    "    def __init__(\n",
    "        self,\n",
    "        name: str,\n",
    "        system_message: SystemMessage,\n",
    "        #model: MyHuggingFaceModel(),\n",
    "        model: llm,\n",
    "        tool_names: List[str],\n",
    "        **tool_kwargs,\n",
    "    ) -> None:\n",
    "        super().__init__(name, system_message, model)\n",
    "        #self.tools = load_tools(tool_names, **tool_kwargs)\n",
    "        self.tools = tool_names\n",
    "\n",
    "    def send(self) -> str:\n",
    "        \"\"\"\n",
    "        Applies the chatmodel to the message history\n",
    "        and returns the message string\n",
    "        \"\"\"\n",
    "        agent_chain = initialize_agent(\n",
    "            self.tools,\n",
    "            self.model,\n",
    "            agent = \"zero-shot-react-description\",\n",
    "            #agent = \"chat-zero-shot-react-description\",\n",
    "            verbose=True,\n",
    "            # memory=ConversationBufferMemory(\n",
    "            #     memory_key=\"chat_history\", return_messages=True\n",
    "            # ),\n",
    "            #max_iterations=2\n",
    "        )\n",
    "        message = AIMessage(\n",
    "            content=agent_chain.run(\n",
    "                input=\"\\n\".join(\n",
    "                    [self.system_message.content] + self.message_history + [self.prefix]\n",
    "                )\n",
    "            )\n",
    "        )\n",
    "\n",
    "        return message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "M26YKubf4KZP"
   },
   "source": [
    "# Define Names of Each Agent\n",
    "\n",
    "Each speaker agent will be the expert of its own country's ESG policies and has access to a tool to find out more about the country's policies. The moderator has no access to tool."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "id": "ILbRwM1a4KZP"
   },
   "outputs": [],
   "source": [
    "# speaker agents names\n",
    "speaker_names = [f\"{country} Public ESG Policies Searcher\" for country in countries_in_query]\n",
    "moderator_name = \"Moderator\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JMbpuV3F4KZR"
   },
   "source": [
    "# Generate System Messages (Role Descriptions for Each Agent)\n",
    "\n",
    "This is used to describe the roles of each agent. Despite writing the description and prompt below, the agents will still continue to simulate the conversation for other members in the chat or try to draw conclusions on its own."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "jt4rhtEt4KZR"
   },
   "outputs": [],
   "source": [
    "conversation_description = f\"\"\"Here is the topic of conversation: {topic}\n",
    "The participants are: {(', ').join(speaker_names)}\"\"\"\n",
    "\n",
    "def generate_system_message(name, country):\n",
    "    return f\"\"\"Here is the topic of conversation: {topic}\n",
    "\n",
    "    Your name is {name}.    \n",
    "    You ONLY give information about this country: {country}.\n",
    "    \n",
    "    Your description is as follows:\n",
    "    \n",
    "    Your goal is to contribute meaningfully to an ESG discussion \n",
    "    and inform the other parties about the relevant ESG policies of your country, NOTHING MORE.\n",
    "    You only give information about your country. You can only obtain information for your country by looking them up with your tool.\n",
    "    If no information is returned by your tool, say you do not know and cannot obtain the information. \n",
    "    Do not come up with information yourself without using a tool.\n",
    "    Do not try to look up information of another country.\n",
    "    Do not speak about another country.\n",
    "    Stop speaking once you have arrived at a final answer.\n",
    "    Do not come up with what other speakers will say.\n",
    "    Do not draw any comparisons or conclusions yourself.\n",
    "    Stop speaking the moment you finish speaking from your perspective. \n",
    "    \"\"\"\n",
    "\n",
    "agent_system_messages = {\n",
    "    name: generate_system_message(name, country)\n",
    "    for name, country in zip(speaker_names, countries_in_query)\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Role Description for Moderator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "bMjiwBaM4KZS",
    "outputId": "3d833bf5-511b-44fa-f745-de7058a44f28"
   },
   "outputs": [],
   "source": [
    "moderator_system_message = f\"\"\"{conversation_description}\n",
    "        You are a moderator moderating a conversation described above.\n",
    "        You can speak directly to each of the participants: {(', ').join(speaker_names)}.\n",
    "        All your knowledge and information comes from the context above.\n",
    "        You do not have any knowledge yourself, so DO NOT add in any knowledge without referencing the message history.\n",
    "        Do not simulate any conversations between speakers.\n",
    "        \n",
    "        When you have enough information FROM THE MESSAGE HISTORY to conclude about the topic, \n",
    "        give a conclusion about the topic and then inform all speakers to stop speaking by ending specifically with \"No further elaboration is needed\".\n",
    "        If you need more information, wait for other participants to speak.\n",
    "        \n",
    "        Stop speaking the moment you finish speaking from your perspective. \n",
    "        Do not say anything else after that. \n",
    "        Do not speak for any other speakers. \n",
    "        Once again, do not simulate any conversations between speakers.\n",
    "        \"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "syQ6Mpg74KZS"
   },
   "source": [
    "# Set Up the 3 Agents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "id": "22I4D9Lb4KZS"
   },
   "outputs": [],
   "source": [
    "agents = [\n",
    "    DialogueAgentWithTools(\n",
    "        name=name,\n",
    "        system_message=SystemMessage(content=system_message),\n",
    "        model=llm,\n",
    "        tool_names=tools,\n",
    "    )\n",
    "    for name, system_message in agent_system_messages.items()\n",
    "]\n",
    "\n",
    "agents += [\n",
    "        DialogueAgent(\n",
    "        name=\"Moderator\",\n",
    "        system_message=SystemMessage(content=moderator_system_message),\n",
    "        model=llm,\n",
    "    )\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "id": "y2LfHH4h4KZS"
   },
   "outputs": [],
   "source": [
    "# logic to let the next agent starts speaking\n",
    "def select_next_speaker(step: int, agents: List[DialogueAgent]) -> int:\n",
    "    idx = (step) % len(agents)\n",
    "    return idx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Start the Conversation\n",
    "\n",
    "Sequence of speaking is country1 agent, country2 agent then moderator and repeat. \n",
    "\n",
    "The moderator is told to end off with \"No further elaboration is needed\" if it has enough information to make a conclusion about the topic, upon seeing this, the while loop below will be stopped.\n",
    "\n",
    "The maximum iterations is 9, which gives each agent the chance to talk 3 times before the moderator concludes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1000
    },
    "id": "7mJGufEU4KZS",
    "outputId": "1320046c-d243-4338-a582-f6310084a179"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\n",
      "\n",
      "############ Singapore Public ESG Policies Searcher is thinking.....\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m I need to find out about Singapore's carbon emissions policies.\n",
      "Action: retrieve_answer_for_country\n",
      "Action Input: [\"What are the carbon emissions policies in Singapore?\", \"Singapore\"]\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m Singapore has implemented various policies to address carbon emissions. The country has updated its Nationally Determined Contribution (NDC) to reduce emissions to around 60 million tonnes of carbon dioxide equivalent (MtCO2e) in 2030 after peaking emissions earlier. Singapore has also raised its national climate target to achieve net zero by 2050. The Ministry of Trade & Industry launched Singapore’s National Hydrogen Strategy to provide a roadmap on utilizing hydrogen as a decarbonization pathway. The Monetary Authority of Singapore established the Sustainable Finance Advisory Panel to help guide MAS on its strategies and initiatives to build a credible and vibrant sustainable finance ecosystem. Manufacturing sectors like electronics, precision engineering, energy and chemicals, aerospace, and logistics aim to grow value-added manufacturing by 50% from 2020 to 2030. Singapore has also signed the Green Economy Agreement with Australia to foster common rules and standards to promote trade and investment in green goods and services. The public sector has committed to achieving net zero emissions around 2045, five years ahead of Singapore’s national target of net zero by 2050, reducing energy and water use by 10% and waste disposed of by 30% respectively in 2030. The public sector has put in measures to green buildings and vehicle fleets, reduce waste, and increase solar energy adoption.\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m I now know the carbon emissions policies in Singapore.\n",
      "Final Answer: Singapore has implemented various policies to address carbon emissions. The country has updated its Nationally Determined Contribution (NDC) to reduce emissions to around 60 million tonnes of carbon dioxide equivalent (MtCO2e) in 2030 after peaking emissions earlier. Singapore has also raised its national climate target to achieve net zero by 2050. The Ministry of Trade & Industry launched Singapore’s National Hydrogen Strategy to provide a roadmap on utilizing hydrogen as a decarbonization pathway. The Monetary Authority of Singapore established the Sustainable Finance Advisory Panel to help guide MAS on its strategies and initiatives to build a credible and vibrant sustainable finance ecosystem. Manufacturing sectors like electronics, precision engineering, energy and chemicals, aerospace, and logistics aim to grow value-added manufacturing by 50% from 2020 to 2030. Singapore has also signed the Green Economy Agreement with Australia to foster common rules and standards to promote trade and investment in green goods and services. The public sector has committed to achieving net zero emissions around 2045, five years ahead of Singapore’s national target of net zero by 2050, reducing energy and water use by 10% and waste disposed of by 30% respectively in 2030. The public sector has put in measures to green buildings and vehicle fleets, reduce waste, and increase solar energy adoption.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "Singapore Public ESG Policies Searcher Speaks: Singapore has implemented various policies to address carbon emissions. The country has updated its Nationally Determined Contribution (NDC) to reduce emissions to around 60 million tonnes of carbon dioxide equivalent (MtCO2e) in 2030 after peaking emissions earlier. Singapore has also raised its national climate target to achieve net zero by 2050. The Ministry of Trade & Industry launched Singapore’s National Hydrogen Strategy to provide a roadmap on utilizing hydrogen as a decarbonization pathway. The Monetary Authority of Singapore established the Sustainable Finance Advisory Panel to help guide MAS on its strategies and initiatives to build a credible and vibrant sustainable finance ecosystem. Manufacturing sectors like electronics, precision engineering, energy and chemicals, aerospace, and logistics aim to grow value-added manufacturing by 50% from 2020 to 2030. Singapore has also signed the Green Economy Agreement with Australia to foster common rules and standards to promote trade and investment in green goods and services. The public sector has committed to achieving net zero emissions around 2045, five years ahead of Singapore’s national target of net zero by 2050, reducing energy and water use by 10% and waste disposed of by 30% respectively in 2030. The public sector has put in measures to green buildings and vehicle fleets, reduce waste, and increase solar energy adoption.\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "############ Malaysia Public ESG Policies Searcher is thinking.....\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m I need to find out about Malaysia's carbon emissions policies.\n",
      "Action: retrieve_answer_for_country\n",
      "Action Input: [\"What are Malaysia's carbon emissions policies?\", \"Malaysia\"]\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3m Malaysia has committed to reducing greenhouse gas emissions to 45% of GDP by 2030 in line with the Paris Agreement. The country also aims to achieve carbon neutrality by 2050 and has proposed a tax deduction of up to RM300,000 for companies that invest in measurement reporting and verification (MRV) related to the development of carbon projects. These expenses can be deducted from the sale of carbon credits traded on the Bursa Carbon Exchange (BCX). Additionally, Malaysia has emphasized waste management practices, learning from global trends and experiences, to further enhance its ESG efforts.\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m I now know Malaysia's carbon emissions policies.\n",
      "Final Answer: Malaysia has committed to reducing greenhouse gas emissions to 45% of GDP by 2030 in line with the Paris Agreement. The country also aims to achieve carbon neutrality by 2050 and has proposed a tax deduction of up to RM300,000 for companies that invest in measurement reporting and verification (MRV) related to the development of carbon projects. These expenses can be deducted from the sale of carbon credits traded on the Bursa Carbon Exchange (BCX). Additionally, Malaysia has emphasized waste management practices, learning from global trends and experiences, to further enhance its ESG efforts.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "Malaysia Public ESG Policies Searcher Speaks: Malaysia has committed to reducing greenhouse gas emissions to 45% of GDP by 2030 in line with the Paris Agreement. The country also aims to achieve carbon neutrality by 2050 and has proposed a tax deduction of up to RM300,000 for companies that invest in measurement reporting and verification (MRV) related to the development of carbon projects. These expenses can be deducted from the sale of carbon credits traded on the Bursa Carbon Exchange (BCX). Additionally, Malaysia has emphasized waste management practices, learning from global trends and experiences, to further enhance its ESG efforts.\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "############ Moderator is thinking.....\n",
      "Moderator Speaks: \n",
      "Singapore Public ESG Policies Searcher, Malaysia Public ESG Policies Searcher, thank you for sharing your knowledge on the carbon emissions policies of your respective countries.\n",
      "Based on the information provided, it appears that both Singapore and Malaysia have committed to reducing greenhouse gas emissions and achieving carbon neutrality by 2050.\n",
      "Singapore has implemented various policies to address carbon emissions, including updating its NDC, establishing a National Hydrogen Strategy, and launching initiatives to build a sustainable finance ecosystem. The public sector in Singapore has also committed to achieving net zero emissions around 2045, reducing energy and water use, and increasing solar energy adoption.\n",
      "On the other hand, Malaysia has committed to reducing greenhouse gas emissions to 45% of GDP by 2030 and achieving carbon neutrality by 2050. The country has also proposed a tax deduction for companies that invest in MRV related to the development of carbon projects and has emphasized waste management practices.\n",
      "In conclusion, both Singapore and Malaysia have taken significant steps to address carbon emissions and achieve carbon neutrality by 2050. However, the specific policies and initiatives implemented by each country differ.\n",
      "No further elaboration is needed.\n"
     ]
    }
   ],
   "source": [
    "# sequence of speaking is country1 agent, country2 agent then moderator and repeat\n",
    "max_iters = 9 # provides 3 rounds of conversation for all 3 parties, 3 ending with the moderator\n",
    "n = 0\n",
    "\n",
    "simulator = DialogueSimulator(agents=agents, selection_function=select_next_speaker)\n",
    "simulator.reset()\n",
    "print(\"\\n\")\n",
    "\n",
    "while n < max_iters:\n",
    "    name, message = simulator.step()\n",
    "    print(f\"{name} Speaks: {message}\")\n",
    "    #The moderator is told to end off with \"No further elaboration is needed\" if it has enough information to make a conclusion about the topic.\n",
    "    if \"No further elaboration is needed\" in message:\n",
    "        break\n",
    "    print(\"\\n\")\n",
    "    n += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "WqOhge7cyQpC"
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}