{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Your First RAQA Application\n",
"\n",
"In this notebook, we'll walk you through each of the components that are involved in a simple RAQA application. \n",
"\n",
"We won't be leveraging any fancy tools, just the OpenAI Python SDK, Numpy, and some classic Python.\n",
"\n",
"> NOTE: This was done with Python 3.11.4."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's look at a rather complicated looking visual representation of a basic RAQA application.\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Imports and Utility \n",
"\n",
"We're just doing some imports and enabling `async` to work within the Jupyter environment here, nothing too crazy!"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"!pip install -q -U numpy matplotlib plotly pandas scipy scikit-learn python-dotenv chainlit==0.7.700 cohere==4.37 openai==1.3.5 tiktoken==0.5.1"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"from aimakerspace.text_utils import TextFileLoader, CharacterTextSplitter\n",
"from aimakerspace.vectordatabase import VectorDatabase\n",
"import asyncio"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"import nest_asyncio\n",
"nest_asyncio.apply()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Documents\n",
"\n",
"We'll be concerning ourselves with this part of the flow in the following section:\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Loading Source Documents\n",
"\n",
"So, first things first, we need some documents to work with. \n",
"\n",
"While we could work directly with the `.txt` files (or whatever file-types you wanted to extend this to) we can instead do some batch processing of those documents at the beginning in order to store them in a more machine compatible format. \n",
"\n",
"In this case, we're going to parse our text file into a single document in memory.\n",
"\n",
"Let's look at the relevant bits of the `TextFileLoader` class:\n",
"\n",
"```python\n",
"def load_file(self):\n",
" with open(self.path, \"r\", encoding=self.encoding) as f:\n",
" self.documents.append(f.read())\n",
"```\n",
"\n",
"We're simply loading the document using the built in `open` method, and storing that output in our `self.documents` list.\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text_loader = TextFileLoader(\"data/KingLear.txt\")\n",
"documents = text_loader.load_documents()\n",
"len(documents)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ACT I\n",
"SCENE I. King Lear's palace.\n",
"Enter KENT, GLOUCESTER, and EDMUND\n",
"KENT\n",
"I thought the king had more affected the Duke of\n",
"Albany than Cornwall.\n",
"GLOUCESTER\n",
"It did always seem so to us: but now, in the\n",
"division of the kingdom, it appears not which of\n",
"the dukes he values most; for equalities are so\n",
"weighed, that curiosity in neither can make choice\n",
"of either's moiety.\n",
"KENT\n",
"Is not this your son, my lord?\n",
"GLOUCESTER\n",
"His breeding, sir, hath been at my charge: I have\n",
"so often blushed to acknowledge him, that now I am\n",
"brazed to it.\n",
"KENT\n",
"I cannot conceive you.\n",
"GLOUCESTER\n",
"Sir, this young fellow's mot\n"
]
}
],
"source": [
"print(documents[0][:600])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Splitting Text Into Chunks\n",
"\n",
"As we can see, there is one document - and it's the entire text of King Lear.\n",
"\n",
"We'll want to chunk the document into smaller parts so it's easier to pass the most relevant snippets to the LLM. \n",
"\n",
"There is no fixed way to split/chunk documents - and you'll need to rely on some intuition as well as knowing your data *very* well in order to build the most robust system.\n",
"\n",
"For this toy example, we'll just split blindly on length. \n",
"\n",
">There's an opportunity to clear up some terminology here, for this course we will be stick to the following: \n",
">\n",
">- \"source documents\" : The `.txt`, `.pdf`, `.html`, ..., files that make up the files and information we start with in its raw format\n",
">- \"document(s)\" : single (or more) text object(s)\n",
">- \"corpus\" : the combination of all of our documents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's take a peek visually at what we're doing here - and why it might be useful:\n",
"\n",
""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you can see (though it's not specifically true in this toy example) the idea of splitting documents is to break them into managable sized chunks that retain the most relevant local context."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'documents' is not defined",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32mc:\\ai\\llmops3\\repos\\vsrepo\\my-first-raqa\\Python RAQA Example.ipynb Cell 14\u001b[0m line \u001b[0;36m2\n\u001b[0;32m 1\u001b[0m text_splitter \u001b[39m=\u001b[39m CharacterTextSplitter()\n\u001b[1;32m----> 2\u001b[0m split_documents \u001b[39m=\u001b[39m text_splitter\u001b[39m.\u001b[39msplit_texts(documents)\n\u001b[0;32m 3\u001b[0m \u001b[39mlen\u001b[39m(split_documents)\n",
"\u001b[1;31mNameError\u001b[0m: name 'documents' is not defined"
]
}
],
"source": [
"text_splitter = CharacterTextSplitter()\n",
"split_documents = text_splitter.split_texts(documents)\n",
"len(split_documents)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's take a look at some of the documents we've managed to split."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[\"\\ufeffACT I\\nSCENE I. King Lear's palace.\\nEnter KENT, GLOUCESTER, and EDMUND\\nKENT\\nI thought the king had more affected the Duke of\\nAlbany than Cornwall.\\nGLOUCESTER\\nIt did always seem so to us: but now, in the\\ndivision of the kingdom, it appears not which of\\nthe dukes he values most; for equalities are so\\nweighed, that curiosity in neither can make choice\\nof either's moiety.\\nKENT\\nIs not this your son, my lord?\\nGLOUCESTER\\nHis breeding, sir, hath been at my charge: I have\\nso often blushed to acknowledge him, that now I am\\nbrazed to it.\\nKENT\\nI cannot conceive you.\\nGLOUCESTER\\nSir, this young fellow's mother could: whereupon\\nshe grew round-wombed, and had, indeed, sir, a son\\nfor her cradle ere she had a husband for her bed.\\nDo you smell a fault?\\nKENT\\nI cannot wish the fault undone, the issue of it\\nbeing so proper.\\nGLOUCESTER\\nBut I have, sir, a son by order of law, some year\\nelder than this, who yet is no dearer in my account:\\nthough this knave came something saucily into the\\nworld before he was se\"]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"split_documents[0:1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Embeddings and Vectors\n",
"\n",
"Next, we have to convert our corpus into a \"machine readable\" format. \n",
"\n",
"Loosely, this means turning the text into numbers. \n",
"\n",
"There are plenty of resources that talk about this process in great detail - I'll leave this [blog](https://txt.cohere.com/sentence-word-embeddings/) from Cohere:AI as a resource if you want to deep dive a bit. \n",
"\n",
"Today, we're going to talk about the actual process of creating, and then storing, these embeddings, and how we can leverage that to intelligently add context to our queries."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"While this is all baked into 1 call - let's look at some of the code that powers this process:\n",
"\n",
"Let's look at our `VectorDatabase().__init__()`:\n",
"\n",
"```python\n",
"def __init__(self, embedding_model: EmbeddingModel = None):\n",
" self.vectors = defaultdict(np.array)\n",
" self.embedding_model = embedding_model or EmbeddingModel()\n",
"```\n",
"\n",
"As you can see - our vectors are merely stored as a dictionary of `np.array` objects.\n",
"\n",
"Secondly, our `VectorDatabase()` has a default `EmbeddingModel()` which is a wrapper for OpenAI's `text-embedding-ada-002` model. \n",
"\n",
"> **Quick Info About `text-embedding-ada-002`**:\n",
"> - It has a context window of **8192** tokens\n",
"> - It returns vectors with dimension **1536**"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import openai\n",
"from getpass import getpass\n",
"\n",
"openai.api_key = getpass(\"OpenAI API Key: \")\n",
"os.environ[\"OPENAI_API_KEY\"] = openai.api_key"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can call the `async_get_embeddings` method of our `EmbeddingModel()` on a list of `str` and receive a list of `float` back!\n",
"\n",
"```python\n",
"async def async_get_embeddings(self, list_of_text: List[str]) -> List[List[float]]:\n",
" return await aget_embeddings(\n",
" list_of_text=list_of_text, engine=self.embeddings_model_name\n",
" )\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We cast those to `np.array` when we build our `VectorDatabase()`:\n",
"\n",
"```python\n",
"async def abuild_from_list(self, list_of_text: List[str]) -> \"VectorDatabase\":\n",
" embeddings = await self.embedding_model.async_get_embeddings(list_of_text)\n",
" for text, embedding in zip(list_of_text, embeddings):\n",
" self.insert(text, np.array(embedding))\n",
" return self\n",
"```\n",
"\n",
"And that's all we need to do!"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"vector_db = VectorDatabase()\n",
"vector_db = asyncio.run(vector_db.abuild_from_list(split_documents))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So, to review what we've done so far in natural language:\n",
"\n",
"1. We load source documents\n",
"2. We split those source documents into smaller chunks (documents)\n",
"3. We send each of those documents to the `text-embedding-ada-002` OpenAI API endpoint\n",
"4. We store each of the text representations with the vector representations as keys/values in a dictionary"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Semantic Similarity\n",
"\n",
"The next step is to be able to query our `VectorDatabase()` with a `str` and have it return to us vectors and text that is most relevant from our corpus. \n",
"\n",
"We're going to use the following process to achieve this in our toy example:\n",
"\n",
"1. We need to embed our query with the same `EmbeddingModel()` as we used to construct our `VectorDatabase()`\n",
"2. We loop through every vector in our `VectorDatabase()` and use a distance measure to compare how related they are\n",
"3. We return a list of the top `k` closest vectors, with their text representations\n",
"\n",
"There's some very heavy optimization that can be done at each of these steps - but let's just focus on the basic pattern in this notebook.\n",
"\n",
"> We are using [cosine similarity](https://www.engati.com/glossary/cosine-similarity) as a distance measure in this example - but there are many many distance measures you could use - like [these](https://flavien-vidal.medium.com/similarity-distances-for-natural-language-processing-16f63cd5ba55)\n",
"\n",
"> We are using a rather inefficient way of calculating relative distance between the query vector and all other vectors - there are more advanced approaches that are much more efficient, like [ANN](https://towardsdatascience.com/comprehensive-guide-to-approximate-nearest-neighbors-algorithms-8b94f057d6b6)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(\"ng] O my good master!\\nKING LEAR\\nPrithee, away.\\nEDGAR\\n'Tis noble Kent, your friend.\\nKING LEAR\\nA plague upon you, murderers, traitors all!\\nI might have saved her; now she's gone for ever!\\nCordelia, Cordelia! stay a little. Ha!\\nWhat is't thou say'st? Her voice was ever soft,\\nGentle, and low, an excellent thing in woman.\\nI kill'd the slave that was a-hanging thee.\\nCaptain\\n'Tis true, my lords, he did.\\nKING LEAR\\nDid I not, fellow?\\nI have seen the day, with my good biting falchion\\nI would have made them skip: I am old now,\\nAnd these same crosses spoil me. Who are you?\\nMine eyes are not o' the best: I'll tell you straight.\\nKENT\\nIf fortune brag of two she loved and hated,\\nOne of them we behold.\\nKING LEAR\\nThis is a dull sight. Are you not Kent?\\nKENT\\nThe same,\\nYour servant Kent: Where is your servant Caius?\\nKING LEAR\\nHe's a good fellow, I can tell you that;\\nHe'll strike, and quickly too: he's dead and rotten.\\nKENT\\nNo, my good lord; I am the very man,--\\nKING LEAR\\nI'll see that straight.\\nKENT\\nThat,\",\n",
" 0.8344666931475856),\n",
" (\",\\nLay comforts to your bosom; and bestow\\nYour needful counsel to our business,\\nWhich craves the instant use.\\nGLOUCESTER\\nI serve you, madam:\\nYour graces are right welcome.\\nExeunt\\n\\nSCENE II. Before Gloucester's castle.\\nEnter KENT and OSWALD, severally\\nOSWALD\\nGood dawning to thee, friend: art of this house?\\nKENT\\nAy.\\nOSWALD\\nWhere may we set our horses?\\nKENT\\nI' the mire.\\nOSWALD\\nPrithee, if thou lovest me, tell me.\\nKENT\\nI love thee not.\\nOSWALD\\nWhy, then, I care not for thee.\\nKENT\\nIf I had thee in Lipsbury pinfold, I would make thee\\ncare for me.\\nOSWALD\\nWhy dost thou use me thus? I know thee not.\\nKENT\\nFellow, I know thee.\\nOSWALD\\nWhat dost thou know me for?\\nKENT\\nA knave; a rascal; an eater of broken meats; a\\nbase, proud, shallow, beggarly, three-suited,\\nhundred-pound, filthy, worsted-stocking knave; a\\nlily-livered, action-taking knave, a whoreson,\\nglass-gazing, super-serviceable finical rogue;\\none-trunk-inheriting slave; one that wouldst be a\\nbawd, in way of good service, and art nothing but\\nth\",\n",
" 0.8218615790372598),\n",
" (\" Caius?\\nKING LEAR\\nHe's a good fellow, I can tell you that;\\nHe'll strike, and quickly too: he's dead and rotten.\\nKENT\\nNo, my good lord; I am the very man,--\\nKING LEAR\\nI'll see that straight.\\nKENT\\nThat, from your first of difference and decay,\\nHave follow'd your sad steps.\\nKING LEAR\\nYou are welcome hither.\\nKENT\\nNor no man else: all's cheerless, dark, and deadly.\\nYour eldest daughters have fordone them selves,\\nAnd desperately are dead.\\nKING LEAR\\nAy, so I think.\\nALBANY\\nHe knows not what he says: and vain it is\\nThat we present us to him.\\nEDGAR\\nVery bootless.\\nEnter a Captain\\n\\nCaptain\\nEdmund is dead, my lord.\\nALBANY\\nThat's but a trifle here.\\nYou lords and noble friends, know our intent.\\nWhat comfort to this great decay may come\\nShall be applied: for us we will resign,\\nDuring the life of this old majesty,\\nTo him our absolute power:\\nTo EDGAR and KENT\\n\\nyou, to your rights:\\nWith boot, and such addition as your honours\\nHave more than merited. All friends shall taste\\nThe wages of their virtue, and \",\n",
" 0.8212563905734079)]"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vector_db.search_by_text(\"Your servant Kent. Where is your servant Caius?\", k=3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Prompts\n",
"\n",
"In the following section, we'll be looking at the role of prompts - and how they help us to guide our application in the right direction.\n",
"\n",
"In this notebook, we're going to rely on the idea of \"zero-shot in-context learning\".\n",
"\n",
"This is a lot of words to say: \"We will ask it to perform our desired task in the prompt, and provide no examples.\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### XYZRolePrompt\n",
"\n",
"Before we do that, let's stop and think a bit about how OpenAI's chat models work. \n",
"\n",
"We know they have roles - as is indicated in the following API [documentation](https://platform.openai.com/docs/api-reference/chat/create#chat/create-messages)\n",
"\n",
"There are three roles, and they function as follows (taken directly from [OpenAI](https://platform.openai.com/docs/guides/gpt/chat-completions-api)): \n",
"\n",
"- `{\"role\" : \"system\"}` : The system message helps set the behavior of the assistant. For example, you can modify the personality of the assistant or provide specific instructions about how it should behave throughout the conversation. However note that the system message is optional and the model’s behavior without a system message is likely to be similar to using a generic message such as \"You are a helpful assistant.\"\n",
"- `{\"role\" : \"user\"}` : The user messages provide requests or comments for the assistant to respond to.\n",
"- `{\"role\" : \"assistant\"}` : Assistant messages store previous assistant responses, but can also be written by you to give examples of desired behavior.\n",
"\n",
"The main idea is this: \n",
"\n",
"1. You start with a system message that outlines how the LLM should respond, what kind of behaviours you can expect from it, and more\n",
"2. Then, you can provide a few examples in the form of \"assistant\"/\"user\" pairs\n",
"3. Then, you prompt the model with the true \"user\" message.\n",
"\n",
"In this example, we'll be forgoing the 2nd step for simplicities sake."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Utility Functions\n",
"\n",
"You'll notice that we're using some utility functions from the `aimakerspace` module - let's take a peek at these and see what they're doing!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### XYZRolePrompt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we have our `system`, `user`, and `assistant` role prompts. \n",
"\n",
"Let's take a peek at what they look like:\n",
"\n",
"```python\n",
"class BasePrompt:\n",
" def __init__(self, prompt):\n",
" \"\"\"\n",
" Initializes the BasePrompt object with a prompt template.\n",
"\n",
" :param prompt: A string that can contain placeholders within curly braces\n",
" \"\"\"\n",
" self.prompt = prompt\n",
" self._pattern = re.compile(r\"\\{([^}]+)\\}\")\n",
"\n",
" def format_prompt(self, **kwargs):\n",
" \"\"\"\n",
" Formats the prompt string using the keyword arguments provided.\n",
"\n",
" :param kwargs: The values to substitute into the prompt string\n",
" :return: The formatted prompt string\n",
" \"\"\"\n",
" matches = self._pattern.findall(self.prompt)\n",
" return self.prompt.format(**{match: kwargs.get(match, \"\") for match in matches})\n",
"\n",
" def get_input_variables(self):\n",
" \"\"\"\n",
" Gets the list of input variable names from the prompt string.\n",
"\n",
" :return: List of input variable names\n",
" \"\"\"\n",
" return self._pattern.findall(self.prompt)\n",
"```\n",
"\n",
"Then we have our `RolePrompt` which laser focuses us on the role pattern found in most API endpoints for LLMs.\n",
"\n",
"```python\n",
"class RolePrompt(BasePrompt):\n",
" def __init__(self, prompt, role: str):\n",
" \"\"\"\n",
" Initializes the RolePrompt object with a prompt template and a role.\n",
"\n",
" :param prompt: A string that can contain placeholders within curly braces\n",
" :param role: The role for the message ('system', 'user', or 'assistant')\n",
" \"\"\"\n",
" super().__init__(prompt)\n",
" self.role = role\n",
"\n",
" def create_message(self, **kwargs):\n",
" \"\"\"\n",
" Creates a message dictionary with a role and a formatted message.\n",
"\n",
" :param kwargs: The values to substitute into the prompt string\n",
" :return: Dictionary containing the role and the formatted message\n",
" \"\"\"\n",
" return {\"role\": self.role, \"content\": self.format_prompt(**kwargs)}\n",
"```\n",
"\n",
"We'll look at how the `SystemRolePrompt` is constructed to get a better idea of how that extension works:\n",
"\n",
"```python\n",
"class SystemRolePrompt(RolePrompt):\n",
" def __init__(self, prompt: str):\n",
" super().__init__(prompt, \"system\")\n",
"```\n",
"\n",
"That pattern is repeated for our `UserRolePrompt` and our `AssistantRolePrompt` as well."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"##### ChatOpenAI"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next we have our model, which is converted to a format analagous to libraries like LangChain and LlamaIndex.\n",
"\n",
"Let's take a peek at how that is constructed:\n",
"\n",
"```python\n",
"class ChatOpenAI:\n",
" def __init__(self, model_name: str = \"gpt-3.5-turbo\"):\n",
" self.model_name = model_name\n",
" self.openai_api_key = os.getenv(\"OPENAI_API_KEY\")\n",
" if self.openai_api_key is None:\n",
" raise ValueError(\"OPENAI_API_KEY is not set\")\n",
"\n",
" def run(self, messages, text_only: bool = True):\n",
" if not isinstance(messages, list):\n",
" raise ValueError(\"messages must be a list\")\n",
"\n",
" openai.api_key = self.openai_api_key\n",
" response = openai.ChatCompletion.create(\n",
" model=self.model_name, messages=messages\n",
" )\n",
"\n",
" if text_only:\n",
" return response.choices[0].message.content\n",
"\n",
" return response\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Creating and Prompting OpenAI's `gpt-3.5-turbo`!\n",
"\n",
"Let's tie all these together and use it to prompt `gpt-3.5-turbo`!"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"from aimakerspace.openai_utils.prompts import (\n",
" UserRolePrompt,\n",
" SystemRolePrompt,\n",
" AssistantRolePrompt,\n",
")\n",
"\n",
"from aimakerspace.openai_utils.chatmodel import ChatOpenAI\n",
"\n",
"chat_openai = ChatOpenAI()\n",
"user_prompt_template = \"{content}\"\n",
"user_role_prompt = UserRolePrompt(user_prompt_template)\n",
"system_prompt_template = (\n",
" \"You are an expert in {expertise}, you always answer in a kind way.\"\n",
")\n",
"system_role_prompt = SystemRolePrompt(system_prompt_template)\n",
"\n",
"messages = [\n",
" user_role_prompt.create_message(\n",
" content=\"What is the best way to write a loop?\"\n",
" ),\n",
" system_role_prompt.create_message(expertise=\"Python\"),\n",
"]\n",
"\n",
"response = chat_openai.run(messages)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The best way to write a loop depends on the specific programming language you are using. However, I can provide some general tips for writing loops that can apply to many languages, including Python:\n",
"\n",
"1. Determine the type of loop you need: There are generally two types of loops: \"for\" loops and \"while\" loops. Use a \"for\" loop when you know the number of iterations in advance, and a \"while\" loop when the number of iterations is uncertain.\n",
"\n",
"2. Define the loop condition: In most cases, a loop should have a defined condition that determines whether the loop should continue or exit. This condition is typically checked before each iteration. Make sure the condition is appropriate for your specific scenario.\n",
"\n",
"3. Initialize loop control variables: If your loop requires variables to control its flow, make sure to initialize them before the loop starts. This ensures the loop starts with the expected initial values.\n",
"\n",
"4. Update loop control variables: When using a loop that relies on control variables, ensure that you update these variables within the loop body. Otherwise, the loop might become infinite or not produce the desired results.\n",
"\n",
"5. Include necessary code in the loop body: Within the loop body, place the code you want to execute during each iteration. This could include calculations, condition checks, or any other desired operations.\n",
"\n",
"6. Ensure proper indentation: Many programming languages, including Python, use indentation to define the scope of the loop body. Make sure to indent the code inside the loop correctly, so it is executed as part of the loop.\n",
"\n",
"7. Exit the loop when appropriate: If there is a condition based on which the loop should terminate, ensure it is properly implemented. Otherwise, an infinite loop may occur, which could lead to unexpected results or even crash your program.\n",
"\n",
"Remember, coding practices and guidelines may vary based on the programming language you are using, so it's always a good idea to consult the documentation or specific best practices for that language.\n"
]
}
],
"source": [
"print(response)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Retrieval Augmented Question Answering Prompt\n",
"\n",
"Now we can create a RAQA prompt - which will help our system behave in a way that makes sense!\n",
"\n",
"There is much you could do here, many tweaks and improvements to be made!"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"RAQA_PROMPT_TEMPLATE = \"\"\"\n",
"Use the provided context to answer the user's query. \n",
"\n",
"You may not answer the user's query unless there is specific context in the following text.\n",
"\n",
"If you do not know the answer, or cannot answer, please respond with \"I don't know\".\n",
"\n",
"Context:\n",
"{context}\n",
"\"\"\"\n",
"\n",
"raqa_prompt = SystemRolePrompt(RAQA_PROMPT_TEMPLATE)\n",
"\n",
"USER_PROMPT_TEMPLATE = \"\"\"\n",
"User Query:\n",
"{user_query}\n",
"\"\"\"\n",
"\n",
"user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)\n",
"\n",
"class RetrievalAugmentedQAPipeline:\n",
" def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:\n",
" self.llm = llm\n",
" self.vector_db_retriever = vector_db_retriever\n",
"\n",
" def run_pipeline(self, user_query: str) -> str:\n",
" context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
" \n",
" context_prompt = \"\"\n",
" for context in context_list:\n",
" context_prompt += context[0] + \"\\n\"\n",
"\n",
" formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)\n",
"\n",
" formatted_user_prompt = user_prompt.create_message(user_query=user_query)\n",
" \n",
" return self.llm.run([formatted_system_prompt, formatted_user_prompt])"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
" vector_db_retriever=vector_db,\n",
" llm=chat_openai\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'King Lear is a character in William Shakespeare\\'s play called \"King Lear.\" He is an aging king who decides to divide his kingdom among his three daughters, Goneril, Regan, and Cordelia. However, his decision leads to a series of tragic events and the unraveling of his sanity.'"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"retrieval_augmented_qa_pipeline.run_pipeline(\"Who is King Lear?\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Visibility Tooling\n",
"\n",
"This is great, but what if we wanted to add some visibility to our pipeline?\n",
"\n",
"Let's use Weights and Biases as a visibility tool!\n",
"\n",
"The first thing we'll need to do is create a Weights and Biases account and get an API key. \n",
"\n",
"You can follow the process outlined [here](https://docs.wandb.ai/quickstart) to do exactly that!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can get the Weights and Biases dependency and add our key to our env. to begin!"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [],
"source": [
"!pip install -q -U wandb"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [],
"source": [
"wandb_key = getpass(\"Weights and Biases API Key: \")\n",
"os.environ[\"WANDB_API_KEY\"] = wandb_key"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"\u001b[34m\u001b[1mwandb\u001b[0m: Currently logged in as: \u001b[33mgarygec8\u001b[0m (\u001b[33mdeepmediamachine\u001b[0m). Use \u001b[1m`wandb login --relogin`\u001b[0m to force relogin\n"
]
},
{
"data": {
"text/html": [
"wandb version 0.16.1 is available! To upgrade, please run:\n",
" $ pip install wandb --upgrade"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"Tracking run with wandb version 0.16.0"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"Run data is saved locally in c:\\ai\\llmops3\\repos\\vsrepo\\my-first-raqa\\wandb\\run-20231205_135828-pd04j1u0"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"Syncing run northern-disco-1 to Weights & Biases (docs) "
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
" View project at https://wandb.ai/deepmediamachine/Visibility%20Example"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
" View run at https://wandb.ai/deepmediamachine/Visibility%20Example/runs/pd04j1u0"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
""
],
"text/plain": [
""
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import wandb\n",
"\n",
"os.environ[\"WANDB_NOTEBOOK_NAME\"] = \"Python RAQA Example.ipynb\"\n",
"wandb.init(project=\"Visibility Example\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can integrate Weights and Biases into our `RetrievalAugmentedQAPipeline`.\n",
"\n",
"```python\n",
"if self.wandb_project:\n",
" root_span = Trace(\n",
" name=\"root_span\",\n",
" kind=\"llm\",\n",
" status_code=status,\n",
" status_message=status_message,\n",
" start_time_ms=start_time,\n",
" end_time_ms=end_time,\n",
" metadata={\n",
" \"token_usage\" : token_usage\n",
" },\n",
" inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
" outputs= {\"response\" : response_text}\n",
" )\n",
"\n",
" root_span.log(name=\"openai_trace\")\n",
"```\n",
"\n",
"The main things to consider here are how to populate the various fields to make sure we're tracking useful information. \n",
"\n",
"We'll use the `text_only` flag to ensure we can get detailed information about our LLM call!\n",
"\n",
"You can check out all the parameters for Weights and Biases `Trace` [here](https://github.com/wandb/wandb/blob/653015a014281f45770aaf43627f64d9c4f04a32/wandb/sdk/data_types/trace_tree.py#L166)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"import datetime\n",
"from wandb.sdk.data_types.trace_tree import Trace\n",
"\n",
"class RetrievalAugmentedQAPipeline:\n",
" def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase, wandb_project = None) -> None:\n",
" self.llm = llm\n",
" self.vector_db_retriever = vector_db_retriever\n",
" self.wandb_project = wandb_project\n",
"\n",
" def run_pipeline(self, user_query: str) -> str:\n",
" context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
" \n",
" context_prompt = \"\"\n",
" for context in context_list:\n",
" context_prompt += context[0] + \"\\n\"\n",
"\n",
" formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)\n",
"\n",
" formatted_user_prompt = user_prompt.create_message(user_query=user_query)\n",
"\n",
" \n",
" start_time = datetime.datetime.now().timestamp() * 1000\n",
"\n",
" try:\n",
" openai_response = self.llm.run([formatted_system_prompt, formatted_user_prompt], text_only=False)\n",
" end_time = datetime.datetime.now().timestamp() * 1000\n",
" status = \"success\"\n",
" status_message = (None, )\n",
" response_text = openai_response.choices[0].message.content\n",
" token_usage = dict(openai_response.usage)\n",
" model = openai_response.model\n",
"\n",
" except Exception as e:\n",
" end_time = datetime.datetime.now().timestamp() * 1000\n",
" status = \"error\"\n",
" status_message = str(e)\n",
" response_text = \"\"\n",
" token_usage = {}\n",
" model = \"\"\n",
"\n",
" if self.wandb_project:\n",
" root_span = Trace(\n",
" name=\"root_span\",\n",
" kind=\"llm\",\n",
" status_code=status,\n",
" status_message=status_message,\n",
" start_time_ms=start_time,\n",
" end_time_ms=end_time,\n",
" metadata={\n",
" \"token_usage\" : token_usage,\n",
" \"model_name\" : model\n",
" },\n",
" inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
" outputs= {\"response\" : response_text}\n",
" )\n",
"\n",
" root_span.log(name=\"openai_trace\")\n",
" \n",
" return response_text if response_text else \"We ran into an error. Please try again later. Full Error Message: \" + status_message"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [],
"source": [
"retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
" vector_db_retriever=vector_db,\n",
" llm=chat_openai,\n",
" wandb_project=\"LLM Visibility Example\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"I don't know.\""
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"retrieval_augmented_qa_pipeline.run_pipeline(\"Who is Batman?\")"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Cordelia dies. In the provided context, King Lear is seen holding Cordelia\\'s dead body in his arms. The text describes how he mourns her, exclaiming \"Howl, howl, howl, howl!\" and expressing his grief over her death.'"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"retrieval_augmented_qa_pipeline.run_pipeline(\"What happens to Cordelia?\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Navigate to the Weights and Biases \"run\" link to see how your LLM is performing!\n",
"\n",
"```\n",
"View run at YOUR LINK HERE\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Conclusion\n",
"\n",
"In this notebook, we've gone through the steps required to create your own simple RAQA application!\n",
"\n",
"Please feel free to extend this as much as you'd like. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Bonus Challenges\n",
"\n",
"Challenge 1: \n",
"- Implement a new distance measure\n",
"- Implement a more efficient vector search\n",
"\n",
"Challenge 2: \n",
"- Create an external VectorStore that can be run/hosted elsewhere\n",
"- Build an adapter for that VectorStore here"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"ename": "ModuleNotFoundError",
"evalue": "No module named 'chainlit'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32mc:\\ai\\llmops3\\repos\\vsrepo\\my-first-raqa\\Python RAQA Example.ipynb Cell 53\u001b[0m line \u001b[0;36m1\n\u001b[1;32m----> 1\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mchainlit\u001b[39;00m \u001b[39mas\u001b[39;00m \u001b[39mcl\u001b[39;00m \u001b[39m# importing chainlit for our app\u001b[39;00m\n\u001b[0;32m 2\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mchainlit\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mprompt\u001b[39;00m \u001b[39mimport\u001b[39;00m Prompt, PromptMessage \u001b[39m# importing prompt tools\u001b[39;00m\n\u001b[0;32m 3\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mchainlit\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mplayground\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mproviders\u001b[39;00m \u001b[39mimport\u001b[39;00m ChatOpenAI \u001b[39m# importing ChatOpenAI tools\u001b[39;00m\n",
"\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'chainlit'"
]
}
],
"source": [
"import chainlit as cl # importing chainlit for our app\n",
"from chainlit.prompt import Prompt, PromptMessage # importing prompt tools\n",
"from chainlit.playground.providers import ChatOpenAI # importing ChatOpenAI tools"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "buildyourownlangchain",
"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.11.5"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}