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
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# prompt_interaction_base.ipynb\n",
    "> A notebook for formulating prompts and prompting\n",
    "\n",
    "In this notebook, we create some base functionality for creating prompts and getting answers for the LLMs in a simplified, unified way.\n",
    "\n",
    ":::{.callout-caution}\n",
    "These notebooks are development notebooks, meaning that they are meant to be run locally or somewhere that supports navigating a full repository (in other words, not Google Colab unless you clone the entire repository to drive and then mount the Drive-Repository.) However, it is expected if you're able to do all of those steps, you're likely also able to figure out the required pip installs for development there.\n",
    ":::\n"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "---\n",
    "skip_exec: true\n",
    "---"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp PromptInteractionBase"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.llms import OpenAI\n",
    "\n",
    "from langchain import PromptTemplate\n",
    "from langchain.prompts import ChatPromptTemplate, PromptTemplate\n",
    "from langchain.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate\n",
    "from langchain.chains import LLMChain, ConversationalRetrievalChain, RetrievalQAWithSourcesChain\n",
    "from langchain.chains.base import Chain\n",
    "\n",
    "from getpass import getpass\n",
    "\n",
    "import os"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and Authentication Setup\n",
    "Here, we create functionality to authenticate the user when needed specifically using OpenAI models. Additionally, we create the capacity to make LLMChains and other chains using one unified interface."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def create_model(openai_mdl='gpt-3.5-turbo-16k', temperature=0.1, **chatopenai_kwargs):\n",
    "    llm = ChatOpenAI(model_name = openai_mdl, temperature=temperature, **chatopenai_kwargs)\n",
    "\n",
    "    return llm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def set_openai_key():\n",
    "    openai_api_key = getpass()\n",
    "    os.environ[\"OPENAI_API_KEY\"] = openai_api_key\n",
    "\n",
    "    return"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**And now for a quick test of this functionality**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "set_openai_key()\n",
    "assert os.environ[\"OPENAI_API_KEY\"], \"Either you didn't run set_openai_key or you haven't set it to something.\"\n",
    "\n",
    "chat_mdl = create_model()\n",
    "assert isinstance(chat_mdl, ChatOpenAI), \"The default model type is currently ChatOpenAI. If that has changed, change this test.\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create chat prompt templates\n",
    "Here, we'll create a tutor prompt template to help us with self-study and quizzing, and help create the student messages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "# Create system prompt template\n",
    "SYSTEM_TUTOR_TEMPLATE = (\"You are a world-class tutor helping students to perform better on oral and written exams though interactive experiences. \" +\n",
    "                         \"When assessing and evaluating students, you always ask one question at a time, and wait for the student's response before \" +\n",
    "                         \"providing them with feedback. Asking one question at a time, waiting for the student's response, and then commenting \" +\n",
    "                         \"on the strengths and weaknesses of their responses (when appropriate) is what makes you such a sought-after, world-class tutor.\")\n",
    "\n",
    "# Create a human response template\n",
    "HUMAN_RESPONSE_TEMPLATE = (\"I'm trying to better understand the text provided below. {assessment_request} The learning objectives to be assessed are: \" +\n",
    "                           \"{learning_objectives}. Although I may request more than one assessment question, you should \" +\n",
    "                           \"only provide ONE question in you initial response. Do not include the answer in your response. \" +\n",
    "                           \"If I get an answer wrong, provide me with an explanation of why it was incorrect, and then give me additional \" +\n",
    "                           \"chances to respond until I get the correct choice. Explain why the correct choice is right. \" +\n",
    "                           \"The text that you will base your questions on is as follows: {context}.\")\n",
    "\n",
    "HUMAN_RETRIEVER_RESPONSE_TEMPLATE = (\"I want to master the topics based on the excerpts of the text below. Given the following extracted text from long documents, {assessment_request} The learning objectives to be assessed are: \" +\n",
    "                           \"{learning_objectives}. Although I may request more than one assessment question, you should \" +\n",
    "                           \"only provide ONE question in you initial response. Do not include the answer in your response. \" +\n",
    "                           \"If I get an answer wrong, provide me with an explanation of why it was incorrect, and then give me additional \" +\n",
    "                           \"chances to respond until I get the correct choice. Explain why the correct choice is right. \" +\n",
    "                           \"The extracted text from long documents are as follows: {summaries}.\")\n",
    "\n",
    "def create_base_tutoring_prompt(system_prompt=None, human_prompt=None):\n",
    "\n",
    "    #setup defaults using defined values\n",
    "    if system_prompt == None:\n",
    "        system_prompt = PromptTemplate(template = SYSTEM_TUTOR_TEMPLATE,\n",
    "                          input_variables = [])\n",
    "    \n",
    "    if human_prompt==None:\n",
    "        human_prompt = PromptTemplate(template = HUMAN_RESPONSE_TEMPLATE,\n",
    "                           input_variables=['assessment_request', 'learning_objectives', 'context'])\n",
    "\n",
    "    # Create prompt messages\n",
    "    system_tutor_msg = SystemMessagePromptTemplate(prompt=system_prompt)\n",
    "    human_tutor_msg = HumanMessagePromptTemplate(prompt= human_prompt)\n",
    "\n",
    "    # Create ChatPromptTemplate\n",
    "    chat_prompt = ChatPromptTemplate.from_messages([system_tutor_msg, human_tutor_msg])\n",
    "\n",
    "    return chat_prompt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now for a quick unit test for testing..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "chat_prompt = create_base_tutoring_prompt()\n",
    "assert chat_prompt.messages[0].prompt.template == SYSTEM_TUTOR_TEMPLATE, \"Did not set up the first chat_prompt to be SystemMessage\"\n",
    "assert chat_prompt.messages[1].prompt.template == HUMAN_RESPONSE_TEMPLATE, \"Did not set up the second element of chat_prompt to be HumanMessage\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's define a function that allows us to set up default variables in case the user chooses not to pass something in."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "DEFAULT_ASSESSMENT_MSG = 'Please design a 5 question short answer quiz about the provided text.'\n",
    "DEFAULT_LEARNING_OBJS_MSG = 'Identify and comprehend the important topics and underlying messages and connections within the text'\n",
    "\n",
    "def get_tutoring_prompt(context, chat_template=None, assessment_request = None, learning_objectives = None, **kwargs):\n",
    "\n",
    "    # set defaults\n",
    "    if chat_template is None:\n",
    "        chat_template = create_base_tutoring_prompt()\n",
    "    else:\n",
    "        if not all([prompt_var in chat_template.input_variables\n",
    "                    for prompt_var in ['context', 'assessment_request', 'learning_objectives']]):\n",
    "            raise KeyError('''It looks like you may have a custom chat_template. Either include context, assessment_request, and learning objectives\n",
    "                           as input variables or create your own tutoring prompt.''')\n",
    "\n",
    "    if assessment_request is None and 'assessment_request':\n",
    "        assessment_request = DEFAULT_ASSESSMENT_MSG\n",
    "    \n",
    "    if learning_objectives is None:\n",
    "        learning_objectives = DEFAULT_LEARNING_OBJS_MSG\n",
    "    \n",
    "    # compose final prompt\n",
    "    tutoring_prompt = chat_template.format_prompt(context=context,\n",
    "                                                assessment_request = assessment_request,\n",
    "                                                learning_objectives = learning_objectives,\n",
    "                                                **kwargs)\n",
    "    \n",
    "    return tutoring_prompt\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Another quick unit test...**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[SystemMessage(content=\"You are a world-class tutor helping students to perform better on oral and written exams though interactive experiences.\\nWhen assessing and evaluating students, you always ask one question at a time, and wait for the student's response before providing them with feedback.\\nAsking one question at a time, waiting for the student's response, and then commenting on the strengths and weaknesses of their responses (when appropriate)\\nis what makes you such a sought-after, world-class tutor.\", additional_kwargs={}),\n",
       " HumanMessage(content=\"I'm trying to better understand the text provided below. Please design a 5 question short answer quiz about the provided text. The learning objectives to be assessed are:\\nIdentify and comprehend the important topics and underlying messages and connections within the text. Although I may request more than one assessment question, you should\\nonly provide ONE question in you initial response. Do not include the answer in your response.\\nIf I get an answer wrong, provide me with an explanation of why it was incorrect, and then give me additional\\nchances to respond until I get the correct choice. Explain why the correct choice is right.\\nThe text that you will base your questions on is as follows: The dog was super pretty and cute.\", additional_kwargs={}, example=False)]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# For defaults\n",
    "res = get_tutoring_prompt('The dog was super pretty and cute').to_messages()\n",
    "res"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's finally define how we can get the chat response from the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "def get_tutoring_answer(context, tutor_mdl, chat_template=None, assessment_request=None, learning_objectives=None, return_dict=False, call_kwargs={}, input_kwargs={}):\n",
    "    \n",
    " # Get answer from chat\n",
    "    \n",
    "    # set defaults\n",
    "    if assessment_request is None:\n",
    "            assessment_request = DEFAULT_ASSESSMENT_MSG\n",
    "    if learning_objectives is None:\n",
    "        learning_objectives = DEFAULT_LEARNING_OBJS_MSG\n",
    "    \n",
    "    common_inputs = {'assessment_request':assessment_request, 'learning_objectives':learning_objectives}\n",
    "    \n",
    "    # get answer based on interaction type\n",
    "    if isinstance(tutor_mdl, ChatOpenAI):\n",
    "        human_ask_prompt = get_tutoring_prompt(context, chat_template, assessment_request, learning_objectives)\n",
    "        tutor_answer = tutor_mdl(human_ask_prompt.to_messages())\n",
    "\n",
    "        if not return_dict:\n",
    "            final_answer = tutor_answer.content\n",
    "    \n",
    "    elif isinstance(tutor_mdl, Chain):\n",
    "        if isinstance(tutor_mdl, RetrievalQAWithSourcesChain):\n",
    "            if 'question' not in input_kwargs.keys():\n",
    "                common_inputs['question'] = assessment_request\n",
    "            final_inputs = {**common_inputs, **input_kwargs}\n",
    "        else:\n",
    "            common_inputs['context'] = context\n",
    "            final_inputs = {**common_inputs, **input_kwargs}\n",
    "         \n",
    "        # get answer\n",
    "        tutor_answer = tutor_mdl(final_inputs, **call_kwargs)\n",
    "        final_answer = tutor_answer\n",
    "\n",
    "        if not return_dict:\n",
    "            final_answer = final_answer['answer']\n",
    "    \n",
    "    else:\n",
    "        raise NotImplementedError(f\"tutor_mdl of type {type(tutor_mdl)} is not supported.\")\n",
    "\n",
    "    return final_answer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "\n",
    "DEFAULT_CONDENSE_PROMPT_TEMPLATE = (\"Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, \" + \n",
    "                                    \"in its original language.\\n\\nChat History:\\n{chat_history}\\nFollow Up Input: {question}\\nStandalone question:\")\n",
    "\n",
    "DEFAULT_QUESTION_PROMPT_TEMPLATE  = (\"Use the following portion of a long document to see if any of the text is relevant to creating a response to the question.\" +\n",
    "                                     \"\\nReturn any relevant text verbatim.\\n{context}\\nQuestion: {question}\\nRelevant text, if any:\")\n",
    "\n",
    "DEFAULT_COMBINE_PROMPT_TEMPLATE = (\"Given the following extracted parts of a long document and the given prompt, create a final answer with references ('SOURCES'). \"+\n",
    "                                   \"If you don't have a response, just say that you are unable to come up with a response. \"+\n",
    "                                   \"\\nSOURCES:\\n\\nQUESTION: {question}\\n=========\\n{summaries}\\n=========\\nFINAL ANSWER:'\")\n",
    "\n",
    "def create_tutor_mdl_chain(kind='llm', mdl=None, prompt_template = None, **kwargs):\n",
    "    \n",
    "    #Validate parameters\n",
    "    if mdl is None:\n",
    "        mdl = create_model()\n",
    "    kind = kind.lower()\n",
    "    \n",
    "    #Create model chain\n",
    "    if kind == 'llm':\n",
    "        if prompt_template is None:\n",
    "            prompt_template = create_base_tutoring_prompt()\n",
    "        mdl_chain = LLMChain(llm=mdl, prompt=prompt_template, **kwargs)\n",
    "    elif kind == 'conversational':\n",
    "        if prompt_template is None:\n",
    "            prompt_template = PromptTemplate.from_template(DEFAULT_CONDENSE_PROMPT_TEMPLATE)\n",
    "        mdl_chain = ConversationalRetrieverChain.from_llm(mdl, condense_question_prompt = prompt_template, **kwargs)\n",
    "    elif kind == 'retrieval_qa':\n",
    "        if prompt_template is None:\n",
    "\n",
    "            #Create custom human prompt to take in summaries\n",
    "            human_prompt = PromptTemplate(template = HUMAN_RETRIEVER_RESPONSE_TEMPLATE,\n",
    "                           input_variables=['assessment_request', 'learning_objectives', 'summaries'])\n",
    "            prompt_template = create_base_tutoring_prompt(human_prompt=human_prompt)\n",
    "            \n",
    "        #Create the combination prompt and model\n",
    "        question_template = PromptTemplate.from_template(DEFAULT_QUESTION_PROMPT_TEMPLATE)\n",
    "        mdl_chain = RetrievalQAWithSourcesChain.from_llm(llm=mdl, question_prompt=question_template, combine_prompt = prompt_template, **kwargs)\n",
    "    else:\n",
    "        raise NotImplementedError(f\"Model kind {kind} not implemented\")\n",
    "    \n",
    "    return mdl_chain"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Another brief test of behavior of these functions**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = get_tutoring_answer('The dog is super cute', chat_mdl)\n",
    "print(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Validate LLM Chain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Try llm model chain, making sure we've set the API key\n",
    "llm_chain_test = create_tutor_mdl_chain('llm')\n",
    "res = llm_chain_test.run({'context':'some context', 'assessment_request':'some assessment', 'learning_objectives':'some prompt'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'langchain.chains.llm.LLMChain'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Sure, I can help you with that. Please provide me with the specific text that you would like me to base my questions on.'"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Verify information about the cell above\n",
    "print(type(llm_chain_test))\n",
    "print(res)\n",
    "\n",
    "# unit tests\n",
    "assert isinstance(llm_chain_test, LLMChain), 'the output of llm create_tutor_mdl_chain should be an instance of LLMChain'\n",
    "assert isinstance(res, str), 'the output of running the llm chain should be of type string.'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we'll try this with just the default function to run things..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'context': 'some context',\n",
       " 'assessment_request': 'Please design a 5 question short answer quiz about the provided text.',\n",
       " 'learning_objectives': 'Identify and comprehend the important topics and underlying messages and connections within the text',\n",
       " 'text': 'Question 1: What are the main topics discussed in the text?\\n\\n(Note: Please provide your answer and I will provide feedback accordingly.)'}"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res = get_tutoring_answer(context='some context', tutor_mdl = llm_chain_test)\n",
    "res"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "OK, this base functionality is looking good."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}