{ "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": [ "\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 }