├── LICENSE ├── README.md ├── cover.png └── dspy rag.ipynb /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DSPy-Chain-of-Thought-RAG 2 | Building a Chain of Thought RAG Model with DSPy, Qdrant and Ollama. 3 | 4 | Run it entirely on your local machine/laptop! 5 | 6 | For a walk through the code and the intent behind this repo read my blog on medium: https://sachinkhandewal.medium.com/prompt-like-a-pro-using-dspy-a-guide-to-build-a-better-local-rag-model-using-dspy-qdrant-and-d8011a3942d9 7 | 8 | ![](https://github.com/sachink1729/DSPy-Chain-of-Thought-RAG/blob/main/cover.png) 9 | -------------------------------------------------------------------------------- /cover.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sachink1729/DSPy-Chain-of-Thought-RAG/5367cb284720330cd9a67e66894bb68f47aa2d0f/cover.png -------------------------------------------------------------------------------- /dspy rag.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Building a Chain of thought of RAG Pipeline using Ollama x llama2, Qdrant and DSPy.\n", 8 | "\n", 9 | "#### Author: Sachin Khandewal" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "## Setup" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "# !pip install dspy-ai\n", 26 | "# !pip install qdrant-client\n", 27 | "# !pip install ollama" 28 | ] 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "## Load the dataset" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 1, 40 | "metadata": {}, 41 | "outputs": [ 42 | { 43 | "name": "stderr", 44 | "output_type": "stream", 45 | "text": [ 46 | "c:\\Users\\ASUS\\anaconda3\\envs\\new\\lib\\site-packages\\datasets\\table.py:1421: FutureWarning: promote has been superseded by promote_options='default'.\n", 47 | " table = cls._concat_blocks(blocks, axis=0)\n" 48 | ] 49 | }, 50 | { 51 | "data": { 52 | "text/plain": [ 53 | "1000" 54 | ] 55 | }, 56 | "execution_count": 1, 57 | "metadata": {}, 58 | "output_type": "execute_result" 59 | } 60 | ], 61 | "source": [ 62 | "from dspy.datasets import HotPotQA\n", 63 | "\n", 64 | "# Load the dataset.\n", 65 | "dataset = HotPotQA(train_seed=1, train_size=1000)\n", 66 | "\n", 67 | "# Tell DSPy that the 'question' field is the input. Any other fields are labels and/or metadata.\n", 68 | "dataset = [x.with_inputs('question') for x in dataset.train]\n", 69 | "\n", 70 | "len(dataset)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 5, 76 | "metadata": {}, 77 | "outputs": [ 78 | { 79 | "data": { 80 | "text/plain": [ 81 | "Example({'question': 'What is the code name for the German offensive that started this Second World War engagement on the Eastern Front (a few hundred kilometers from Moscow) between Soviet and German forces, which included 102nd Infantry Division?', 'answer': 'Operation Citadel'}) (input_keys={'question'})" 82 | ] 83 | }, 84 | "execution_count": 5, 85 | "metadata": {}, 86 | "output_type": "execute_result" 87 | } 88 | ], 89 | "source": [ 90 | "dataset[9]" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": 6, 96 | "metadata": {}, 97 | "outputs": [ 98 | { 99 | "data": { 100 | "text/plain": [ 101 | "('What is a block away from the arena where the Baltimore Blast play their games?',\n", 102 | " 'Baltimore Convention Center')" 103 | ] 104 | }, 105 | "execution_count": 6, 106 | "metadata": {}, 107 | "output_type": "execute_result" 108 | } 109 | ], 110 | "source": [ 111 | "dataset[300].question, dataset[300].answer" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": 7, 117 | "metadata": {}, 118 | "outputs": [], 119 | "source": [ 120 | "# import torch\n", 121 | "# torch.cuda.is_available()" 122 | ] 123 | }, 124 | { 125 | "cell_type": "markdown", 126 | "metadata": {}, 127 | "source": [ 128 | "## Initialize the retriever using Qdrant" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": 8, 134 | "metadata": {}, 135 | "outputs": [ 136 | { 137 | "name": "stderr", 138 | "output_type": "stream", 139 | "text": [ 140 | "\u001b[32m2024-03-20 20:03:08.472\u001b[0m | \u001b[33m\u001b[1mWARNING \u001b[0m | \u001b[36mfastembed.embedding\u001b[0m:\u001b[36m\u001b[0m:\u001b[36m7\u001b[0m - \u001b[33m\u001b[1mDefaultEmbedding, FlagEmbedding, JinaEmbedding are deprecated. Use TextEmbedding instead.\u001b[0m\n", 141 | "100%|██████████| 77.7M/77.7M [00:23<00:00, 3.35MiB/s]\n" 142 | ] 143 | } 144 | ], 145 | "source": [ 146 | "from dspy.retrieve.qdrant_rm import QdrantRM\n", 147 | "from qdrant_client import QdrantClient\n", 148 | " \n", 149 | "qdrant_client = QdrantClient(\":memory:\") # loads in memory for this session\n", 150 | "\n", 151 | "docs = [x.question + \" -> \" + x.answer for x in dataset]\n", 152 | "\n", 153 | "ids = list(range(0,len(docs)))\n", 154 | "\n", 155 | "\n", 156 | "qdrant_client.add(\n", 157 | " collection_name=\"hotpotqa\",\n", 158 | " documents=docs,\n", 159 | " ids=ids\n", 160 | " )\n", 161 | "\n", 162 | "\n", 163 | "qdrant_retriever_model = QdrantRM(\"hotpotqa\", qdrant_client, k=3)" 164 | ] 165 | }, 166 | { 167 | "cell_type": "markdown", 168 | "metadata": {}, 169 | "source": [ 170 | "## Load the Ollama model\n", 171 | "\n", 172 | "Pre-requisites: should have downlaoded the Ollama application from: https://ollama.com/download/windows\n", 173 | "\n", 174 | "For Windows you can follow these steps:\n", 175 | "1) To download it, go to: Download Ollama on Windows. \n", 176 | "2) Install it on your system.\n", 177 | "3) After installing, you can open the command prompt and type “ollama pull llama2”, which will download the latest quantized image for Llama2; by default, it pulls a 7B model.\n", 178 | "4) You will see the Ollama icon in your hidden icons, which means that you can run Ollama models now!\n" 179 | ] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "execution_count": 9, 184 | "metadata": {}, 185 | "outputs": [], 186 | "source": [ 187 | "import dspy\n", 188 | "ollama_model = dspy.OllamaLocal(model=\"llama2\",model_type='text',\n", 189 | " max_tokens=350,\n", 190 | " temperature=0.7,\n", 191 | " top_p=0.9, frequency_penalty=1.17, top_k=40)" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": {}, 197 | "source": [ 198 | "Try out one example before proceeding" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": 10, 204 | "metadata": {}, 205 | "outputs": [ 206 | { 207 | "data": { 208 | "text/plain": [ 209 | "[\"Interstellar is a 2014 science fiction film directed by Christopher Nolan that follows a group of astronauts on a mission to travel through wormholes in search of a new habitable planet for humanity. Here is the general plot outline:\\n\\nIn the near future, Earth is facing an unprecedented crisis as crops are failing and food supplies are running low. The world's top scientists, led by Dr. Josep Mendes (Michael Caine), are unable to find a solution to this problem, which threatens the survival of humanity.\\n\\nEnter Cooper (Matthew McConaughey), a former NASA pilot who is recruited for a dangerous mission through wormholes in search of a new habitable planet. Cooper's daughter Murph (Jessica Chastain) is a brilliant young girl who has been struggling to understand the equations that could potentially save Earth, and her father's journey becomes crucial to her research.\\n\\nCooper and his team, which includes Dr. Stone (Stephen Henderson), Amelia Brand (Anne Hathaway), and Romilly (David Gyasi), embark on a dangerous journey through the wormholes, encountering various obstacles along the way. They also encounter strange occurrences that challenge their understanding of time and space.\\n\\nAs Cooper travels through the wormholes, he experiences events in different dimensions and timelines, which affect his perception of reality. Back on Earth, Murph continues her research and discovers a hidden message from her father that could hold the key to saving humanity.\\n\\nThe film's\"]" 210 | ] 211 | }, 212 | "execution_count": 10, 213 | "metadata": {}, 214 | "output_type": "execute_result" 215 | } 216 | ], 217 | "source": [ 218 | "ollama_model(\"tell me about interstellar's plot\")" 219 | ] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "metadata": {}, 224 | "source": [ 225 | "## Get Top Passages from the retriever" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": 11, 231 | "metadata": {}, 232 | "outputs": [ 233 | { 234 | "name": "stdout", 235 | "output_type": "stream", 236 | "text": [ 237 | "Top 3 passages for question: What was a previous unoffical name for the high performance variant of Audi's compact executive car? \n", 238 | " ------------------------------ \n", 239 | "\n", 240 | "1] What was a previous unoffical name for the high performance variant of Audi's compact executive car? -> Audi Ur-S4 \n", 241 | "\n", 242 | "2] What car models used the same Saxomat clutch as the automobiles produced by former East German auto maker VEB Sachsenring Automobilwerke Zwickau in Zwickau, Saxony? -> Fiat 1800, Lancia Flaminia, Saab 93, Borgward Isabella, Goliath/Hansa 1100, Auto Union 1000, Ford Taunus \n", 243 | "\n", 244 | "3] William Sachiti is the founder of the company that is a UK competitor to the major automaker based in what city? -> Palo Alto \n", 245 | "\n" 246 | ] 247 | } 248 | ], 249 | "source": [ 250 | "import dspy\n", 251 | "\n", 252 | "dspy.settings.configure(rm=qdrant_retriever_model, lm=ollama_model)\n", 253 | "\n", 254 | "dev_example = dataset[100]\n", 255 | "\n", 256 | "def get_top_passages(question):\n", 257 | " retrieve = dspy.Retrieve(k=3)\n", 258 | " topK_passages = retrieve(question,k=3).passages\n", 259 | " print(f\"Top {retrieve.k} passages for question: {question} \\n\", '-' * 30, '\\n')\n", 260 | " for idx, passage in enumerate(topK_passages):\n", 261 | " print(f'{idx+1}]', passage, '\\n')\n", 262 | "\n", 263 | "get_top_passages(dev_example.question)" 264 | ] 265 | }, 266 | { 267 | "cell_type": "markdown", 268 | "metadata": {}, 269 | "source": [ 270 | "## Define Signatures for Input and Output" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": 12, 276 | "metadata": {}, 277 | "outputs": [], 278 | "source": [ 279 | "class GenerateAnswer(dspy.Signature):\n", 280 | " \"\"\"Answer questions with short factoid answers.\"\"\"\n", 281 | "\n", 282 | " context = dspy.InputField(desc=\"may or maynot contain relevant facts or answer keywords\")\n", 283 | " question = dspy.InputField()\n", 284 | " answer = dspy.OutputField(desc=\"an answer between 10 to 20 words\")" 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": 13, 290 | "metadata": {}, 291 | "outputs": [], 292 | "source": [ 293 | "ga = GenerateAnswer(context=\"My name is sachin and I like writing blogs\", question=\"What is my name?\", answer=\"Sachin\")" 294 | ] 295 | }, 296 | { 297 | "cell_type": "code", 298 | "execution_count": 14, 299 | "metadata": {}, 300 | "outputs": [ 301 | { 302 | "name": "stdout", 303 | "output_type": "stream", 304 | "text": [ 305 | " answer\n", 306 | " instructions='Answer questions with short factoid answers.'\n", 307 | " context = Field(annotation=str required=True json_schema_extra={'desc': 'may or maynot contain relevant facts or answer keywords', '__dspy_field_type': 'input', 'prefix': 'Context:'})\n", 308 | " question = Field(annotation=str required=True json_schema_extra={'__dspy_field_type': 'input', 'prefix': 'Question:', 'desc': '${question}'})\n", 309 | " answer = Field(annotation=str required=True json_schema_extra={'desc': 'an answer between 10 to 20 words', '__dspy_field_type': 'output', 'prefix': 'Answer:'})\n", 310 | ")>\n" 311 | ] 312 | } 313 | ], 314 | "source": [ 315 | "print(ga.model_construct)" 316 | ] 317 | }, 318 | { 319 | "cell_type": "markdown", 320 | "metadata": {}, 321 | "source": [ 322 | "## Create a DSPy CoT Module" 323 | ] 324 | }, 325 | { 326 | "cell_type": "code", 327 | "execution_count": 15, 328 | "metadata": {}, 329 | "outputs": [], 330 | "source": [ 331 | "class RAG(dspy.Module):\n", 332 | " def __init__(self, num_passages=3):\n", 333 | " super().__init__()\n", 334 | "\n", 335 | " self.retrieve = dspy.Retrieve(k=num_passages)\n", 336 | " self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n", 337 | "\n", 338 | " def forward(self, question):\n", 339 | " context = self.retrieve(question).passages\n", 340 | " prediction = self.generate_answer(context=context, question=question)\n", 341 | " return dspy.Prediction(context=context, answer=prediction.answer)" 342 | ] 343 | }, 344 | { 345 | "cell_type": "markdown", 346 | "metadata": {}, 347 | "source": [ 348 | "Let's call the RAG object" 349 | ] 350 | }, 351 | { 352 | "cell_type": "code", 353 | "execution_count": 130, 354 | "metadata": {}, 355 | "outputs": [], 356 | "source": [ 357 | "uncompiled_rag = RAG()" 358 | ] 359 | }, 360 | { 361 | "cell_type": "markdown", 362 | "metadata": {}, 363 | "source": [ 364 | "Define some datapoints from which we can ask CoT questions" 365 | ] 366 | }, 367 | { 368 | "cell_type": "code", 369 | "execution_count": 19, 370 | "metadata": {}, 371 | "outputs": [ 372 | { 373 | "data": { 374 | "text/plain": [ 375 | "(Example({'question': \"Who has been on a British television music competition show and was was most popular in the 80's with the pop band 'Culture Club'?\", 'answer': \"George Alan O'Dowd\"}) (input_keys={'question'}),\n", 376 | " Example({'question': \"What was a previous unoffical name for the high performance variant of Audi's compact executive car?\", 'answer': 'Audi Ur-S4'}) (input_keys={'question'}),\n", 377 | " Example({'question': 'Which is taller, the Empire State Building or the Bank of America Tower?', 'answer': 'The Empire State Building'}) (input_keys={'question'}))" 378 | ] 379 | }, 380 | "execution_count": 19, 381 | "metadata": {}, 382 | "output_type": "execute_result" 383 | } 384 | ], 385 | "source": [ 386 | "dataset[91],dataset[100],dataset[6]" 387 | ] 388 | }, 389 | { 390 | "cell_type": "markdown", 391 | "metadata": {}, 392 | "source": [ 393 | "## Let's run the queries now" 394 | ] 395 | }, 396 | { 397 | "cell_type": "code", 398 | "execution_count": 133, 399 | "metadata": {}, 400 | "outputs": [ 401 | { 402 | "name": "stdout", 403 | "output_type": "stream", 404 | "text": [ 405 | "No, George Alan O'Dowd was not the most popular in the late 2000s with his rock band.\n" 406 | ] 407 | } 408 | ], 409 | "source": [ 410 | "my_question = \"Was George Alan O'Dowd the most popular in the late 2000s with his rock band?\"\n", 411 | "# my_question = \"which segment of Audi's car was named as Ur-S4?\"\n", 412 | "# my_question = \"is Bank of America Tower taller than empire state building?\"\n", 413 | "\n", 414 | "# get_top_passages(my_question)\n", 415 | "\n", 416 | "response = uncompiled_rag(my_question)\n", 417 | "print(response.answer)" 418 | ] 419 | }, 420 | { 421 | "cell_type": "markdown", 422 | "metadata": {}, 423 | "source": [ 424 | "To inspect the prompt internally" 425 | ] 426 | }, 427 | { 428 | "cell_type": "code", 429 | "execution_count": 134, 430 | "metadata": {}, 431 | "outputs": [ 432 | { 433 | "name": "stdout", 434 | "output_type": "stream", 435 | "text": [ 436 | "\n", 437 | "\n", 438 | "\n", 439 | "\n", 440 | "Answer questions with short factoid answers.\n", 441 | "\n", 442 | "---\n", 443 | "\n", 444 | "Follow the following format.\n", 445 | "\n", 446 | "Context: may or maynot contain relevant facts or answer keywords\n", 447 | "\n", 448 | "Question: ${question}\n", 449 | "\n", 450 | "Reasoning: Let's think step by step in order to ${produce the answer}. We ...\n", 451 | "\n", 452 | "Answer: an answer between 10 to 20 words\n", 453 | "\n", 454 | "---\n", 455 | "\n", 456 | "Context:\n", 457 | "[1] «Who has been on a British television music competition show and was was most popular in the 80's with the pop band 'Culture Club'? -> George Alan O'Dowd»\n", 458 | "[2] «Who was dubbed the father of the type of rock music that emerged from post-punk in the late 1970s? -> Brian Healy»\n", 459 | "[3] «Alan Forbes has done posters for an American rock band that formed in 1996 in what city in California? -> Palm Desert»\n", 460 | "\n", 461 | "Question: Was George Alan O'Dowd the most popular in the late 2000s with his rock band?\n", 462 | "\n", 463 | "Reasoning: Let's think step by step in order to Answer: No, George Alan O'Dowd was not the most popular in the late 2000s. He was active and popular in the 1980s with his pop band Culture Club.\n", 464 | "\n", 465 | "Answer:\u001b[32m No, George Alan O'Dowd was not the most popular in the late 2000s with his rock band.\u001b[0m\n", 466 | "\n", 467 | "\n", 468 | "\n" 469 | ] 470 | } 471 | ], 472 | "source": [ 473 | "ollama_model.inspect_history(n=1)" 474 | ] 475 | }, 476 | { 477 | "cell_type": "markdown", 478 | "metadata": {}, 479 | "source": [ 480 | "## ADVANCED (Using teleprompters to train the CoT model)" 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": 98, 486 | "metadata": {}, 487 | "outputs": [ 488 | { 489 | "name": "stderr", 490 | "output_type": "stream", 491 | "text": [ 492 | "100%|██████████| 3/3 [02:44<00:00, 54.95s/it]" 493 | ] 494 | }, 495 | { 496 | "name": "stdout", 497 | "output_type": "stream", 498 | "text": [ 499 | "Bootstrapped 1 full traces after 3 examples in round 0.\n" 500 | ] 501 | }, 502 | { 503 | "name": "stderr", 504 | "output_type": "stream", 505 | "text": [ 506 | "\n" 507 | ] 508 | } 509 | ], 510 | "source": [ 511 | "# compile\n", 512 | "\n", 513 | "dataset_dev = [dataset[91],\n", 514 | "dataset[100],\n", 515 | "dataset[6]]\n", 516 | "\n", 517 | "from dspy.teleprompt import BootstrapFewShot\n", 518 | "\n", 519 | "# Validation logic: check that the predicted answer is correct.\n", 520 | "# Also check that the retrieved context does actually contain that answer.\n", 521 | "def validate_context_and_answer(example, pred, trace=None):\n", 522 | " answer_EM = dspy.evaluate.answer_exact_match(example, pred)\n", 523 | " answer_PM = dspy.evaluate.answer_passage_match(example, pred)\n", 524 | " return answer_EM and answer_PM\n", 525 | "\n", 526 | "# Set up a basic teleprompter, which will compile our RAG program.\n", 527 | "teleprompter = BootstrapFewShot(metric=validate_context_and_answer)\n", 528 | "\n", 529 | "# Compile!\n", 530 | "compiled_rag = teleprompter.compile(RAG(), dataset=dataset_dev)" 531 | ] 532 | }, 533 | { 534 | "cell_type": "code", 535 | "execution_count": 102, 536 | "metadata": {}, 537 | "outputs": [], 538 | "source": [ 539 | "# Ask any question you like to this simple RAG program.\n", 540 | "\n", 541 | "my_question = \"Was George Alan O'Dowd the most popular in the early 1980s with his pop band?\"\n", 542 | "# my_question = \"which segment of Audi's car was named as Ur-S4?\"\n", 543 | "# my_question = \"is Bank of America Tower taller than empire state building?\"\n", 544 | "\n", 545 | "# get_top_passages(my_question)\n", 546 | "\n", 547 | "# Get the prediction. This contains `pred.context` and `pred.answer`.\n", 548 | "pred = compiled_rag(my_question)\n", 549 | "\n", 550 | "# Print the contexts and the answer.\n", 551 | "print(f\"Question: {my_question}\")\n", 552 | "print(f\"Predicted Answer: {pred.answer}\")\n", 553 | "print(f\"Retrieved Contexts (truncated): {[c[:200] + '...' for c in pred.context]}\")" 554 | ] 555 | }, 556 | { 557 | "cell_type": "code", 558 | "execution_count": 101, 559 | "metadata": {}, 560 | "outputs": [ 561 | { 562 | "name": "stdout", 563 | "output_type": "stream", 564 | "text": [ 565 | "\n", 566 | "\n", 567 | "\n", 568 | "\n", 569 | "Given the fields `context`, `question`, produce the fields `answer`.\n", 570 | "\n", 571 | "---\n", 572 | "\n", 573 | "Question: Which is taller, the Empire State Building or the Bank of America Tower?\n", 574 | "Answer: The Empire State Building\n", 575 | "\n", 576 | "Question: What was a previous unoffical name for the high performance variant of Audi's compact executive car?\n", 577 | "Answer: Audi Ur-S4\n", 578 | "\n", 579 | "---\n", 580 | "\n", 581 | "Follow the following format.\n", 582 | "\n", 583 | "Context: ${context}\n", 584 | "\n", 585 | "Question: ${question}\n", 586 | "\n", 587 | "Reasoning: Let's think step by step in order to ${produce the answer}. We ...\n", 588 | "\n", 589 | "Answer: ${answer}\n", 590 | "\n", 591 | "---\n", 592 | "\n", 593 | "Context:\n", 594 | "[1] «Who has been on a British television music competition show and was was most popular in the 80's with the pop band 'Culture Club'? -> George Alan O'Dowd»\n", 595 | "[2] «The Fridge had booked such acts as the English singer and DJ who was the lead singer of what pop band? -> Culture Club»\n", 596 | "[3] «Celebration was recorded by the singer who was a leading presence when what cable channel premiered? -> MTV»\n", 597 | "\n", 598 | "Question: Who has been on a British television music competition show and was was most popular in the 80's with the pop band 'Culture Club'?\n", 599 | "\n", 600 | "Reasoning: Let's think step by step in order to Context: [1] «Who has been on a British television music competition show and was was most popular in the 80's with the pop band 'Culture Club'? -> George Alan O'Dowd» [2] «The Fridge had booked such acts as the English singer and DJ who was the lead singer of what pop band? -> Culture Club» [3] «Celebration was recorded by the singer who was a leading presence when what cable channel premiered? -> MTV» Question: Who has been on a British television music competition show and was was most popular in the 80's with the pop band 'Culture Club'? Reasoning: Let's think step by step in order to answer this question. We know from [1] that George Alan O'Dowd has been on a British television music competition show. From [2], we know that Culture Club was a popular pop band in the 80's. Therefore, the answer must be George Alan O'Dowd, who was the lead singer of Culture Club.\n", 601 | "\n", 602 | "Answer: George Alan O'Dowd\n", 603 | "\n", 604 | "---\n", 605 | "\n", 606 | "Context:\n", 607 | "[1] «Who has been on a British television music competition show and was was most popular in the 80's with the pop band 'Culture Club'? -> George Alan O'Dowd»\n", 608 | "[2] «The Fridge had booked such acts as the English singer and DJ who was the lead singer of what pop band? -> Culture Club»\n", 609 | "[3] «What singer, best known for his recording of the song \"Raindrops Keep Fallin' on My Head\", had his single \"Most of All\" reach #2 on the \"Billboard\" Adult Contemporary singles chart in 1970? -> B. J. Thomas»\n", 610 | "\n", 611 | "Question: Was George Alan O'Dowd the most popular in the late 1980s with his pop band?\n", 612 | "\n", 613 | "Reasoning: Let's think step by step in order to\u001b[32m Context: [1] «Who has been on a British television music competition show and was was most popular in the 80's with the pop band 'Culture Club'? -> George Alan O'Dowd» [2] «The Fridge had booked such acts as the English singer and DJ who was the lead singer of what pop band? -> Culture Club» [3] «What singer, best known for his recording of the song \"Raindrops Keep Fallin' on My Head\", had his single \"Most of All\" reach #2 on the \"Billboard\" Adult Contemporary singles chart in 1970? -> B. J. Thomas»\n", 614 | "Question: Was George Alan O'Dowd the most popular in the late 1980s with his pop band?\n", 615 | "Reasoning: Let's think step by step in order to answer this question. We know from [1] that George Alan O'Dowd was the lead singer of Culture Club, which was a popular pop band in the 80's. However, we also know from [3] that B. J. Thomas was more popular than George Alan O'Dowd in the late 70's and early 80's. Therefore, the answer must be no, George Alan O'Dowd was not the most popular pop band leader in the late 1980s.\n", 616 | "\n", 617 | "Answer: No\u001b[0m\n", 618 | "\n", 619 | "\n", 620 | "\n" 621 | ] 622 | } 623 | ], 624 | "source": [ 625 | "ollama_model.inspect_history(1)" 626 | ] 627 | }, 628 | { 629 | "cell_type": "code", 630 | "execution_count": null, 631 | "metadata": {}, 632 | "outputs": [], 633 | "source": [] 634 | } 635 | ], 636 | "metadata": { 637 | "kernelspec": { 638 | "display_name": "new", 639 | "language": "python", 640 | "name": "python3" 641 | }, 642 | "language_info": { 643 | "codemirror_mode": { 644 | "name": "ipython", 645 | "version": 3 646 | }, 647 | "file_extension": ".py", 648 | "mimetype": "text/x-python", 649 | "name": "python", 650 | "nbconvert_exporter": "python", 651 | "pygments_lexer": "ipython3", 652 | "version": "3.10.13" 653 | } 654 | }, 655 | "nbformat": 4, 656 | "nbformat_minor": 2 657 | } 658 | --------------------------------------------------------------------------------