Commit
·
98f99ea
0
Parent(s):
init commit
Browse files- .env.sample +1 -0
- .ipynb_checkpoints/Python RAQA Example-checkpoint.ipynb +971 -0
- Dockerfile +11 -0
- Python RAQA Example.ipynb +0 -0
- README.md +19 -0
- aimakerspace/__init__.py +0 -0
- aimakerspace/__pycache__/__init__.cpython-311.pyc +0 -0
- aimakerspace/__pycache__/text_utils.cpython-311.pyc +0 -0
- aimakerspace/__pycache__/vectordatabase.cpython-311.pyc +0 -0
- aimakerspace/openai_utils/__init__.py +0 -0
- aimakerspace/openai_utils/__pycache__/__init__.cpython-311.pyc +0 -0
- aimakerspace/openai_utils/__pycache__/chatmodel.cpython-311.pyc +0 -0
- aimakerspace/openai_utils/__pycache__/embedding.cpython-311.pyc +0 -0
- aimakerspace/openai_utils/__pycache__/prompts.cpython-311.pyc +0 -0
- aimakerspace/openai_utils/chatmodel.py +27 -0
- aimakerspace/openai_utils/embedding.py +52 -0
- aimakerspace/openai_utils/prompts.py +75 -0
- aimakerspace/text_utils.py +77 -0
- aimakerspace/vectordatabase.py +81 -0
- app.py +114 -0
- data/KingLear.txt +0 -0
- images/docchain_img.png +0 -0
- images/raqaapp_img.png +0 -0
- images/texsplitter_img.png +0 -0
- requirements.txt +9 -0
.env.sample
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
OPENAI_API_KEY=###
|
.ipynb_checkpoints/Python RAQA Example-checkpoint.ipynb
ADDED
@@ -0,0 +1,971 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {},
|
6 |
+
"source": [
|
7 |
+
"# Your First RAQA Application\n",
|
8 |
+
"\n",
|
9 |
+
"In this notebook, we'll walk you through each of the components that are involved in a simple RAQA application. \n",
|
10 |
+
"\n",
|
11 |
+
"We won't be leveraging any fancy tools, just the OpenAI Python SDK, Numpy, and some classic Python.\n",
|
12 |
+
"\n",
|
13 |
+
"> NOTE: This was done with Python 3.11.4."
|
14 |
+
]
|
15 |
+
},
|
16 |
+
{
|
17 |
+
"cell_type": "markdown",
|
18 |
+
"metadata": {},
|
19 |
+
"source": [
|
20 |
+
"Let's look at a rather complicated looking visual representation of a basic RAQA application.\n",
|
21 |
+
"\n",
|
22 |
+
"<img src=\"https://i.imgur.com/LCNkd1A.png\" />"
|
23 |
+
]
|
24 |
+
},
|
25 |
+
{
|
26 |
+
"cell_type": "markdown",
|
27 |
+
"metadata": {},
|
28 |
+
"source": [
|
29 |
+
"### Imports and Utility \n",
|
30 |
+
"\n",
|
31 |
+
"We're just doing some imports and enabling `async` to work within the Jupyter environment here, nothing too crazy!"
|
32 |
+
]
|
33 |
+
},
|
34 |
+
{
|
35 |
+
"cell_type": "code",
|
36 |
+
"execution_count": 1,
|
37 |
+
"metadata": {},
|
38 |
+
"outputs": [],
|
39 |
+
"source": [
|
40 |
+
"!pip install -q -U numpy matplotlib plotly pandas scipy scikit-learn openai python-dotenv"
|
41 |
+
]
|
42 |
+
},
|
43 |
+
{
|
44 |
+
"cell_type": "code",
|
45 |
+
"execution_count": 2,
|
46 |
+
"metadata": {},
|
47 |
+
"outputs": [],
|
48 |
+
"source": [
|
49 |
+
"from aimakerspace.text_utils import TextFileLoader, CharacterTextSplitter\n",
|
50 |
+
"from aimakerspace.vectordatabase import VectorDatabase\n",
|
51 |
+
"import asyncio"
|
52 |
+
]
|
53 |
+
},
|
54 |
+
{
|
55 |
+
"cell_type": "code",
|
56 |
+
"execution_count": 3,
|
57 |
+
"metadata": {},
|
58 |
+
"outputs": [],
|
59 |
+
"source": [
|
60 |
+
"import nest_asyncio\n",
|
61 |
+
"nest_asyncio.apply()"
|
62 |
+
]
|
63 |
+
},
|
64 |
+
{
|
65 |
+
"cell_type": "markdown",
|
66 |
+
"metadata": {},
|
67 |
+
"source": [
|
68 |
+
"# Documents\n",
|
69 |
+
"\n",
|
70 |
+
"We'll be concerning ourselves with this part of the flow in the following section:\n",
|
71 |
+
"\n",
|
72 |
+
"<img src=\"https://i.imgur.com/wBYB2x3.png\" />"
|
73 |
+
]
|
74 |
+
},
|
75 |
+
{
|
76 |
+
"cell_type": "markdown",
|
77 |
+
"metadata": {},
|
78 |
+
"source": [
|
79 |
+
"### Loading Source Documents\n",
|
80 |
+
"\n",
|
81 |
+
"So, first things first, we need some documents to work with. \n",
|
82 |
+
"\n",
|
83 |
+
"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",
|
84 |
+
"\n",
|
85 |
+
"In this case, we're going to parse our text file into a single document in memory.\n",
|
86 |
+
"\n",
|
87 |
+
"Let's look at the relevant bits of the `TextFileLoader` class:\n",
|
88 |
+
"\n",
|
89 |
+
"```python\n",
|
90 |
+
"def load_file(self):\n",
|
91 |
+
" with open(self.path, \"r\", encoding=self.encoding) as f:\n",
|
92 |
+
" self.documents.append(f.read())\n",
|
93 |
+
"```\n",
|
94 |
+
"\n",
|
95 |
+
"We're simply loading the document using the built in `open` method, and storing that output in our `self.documents` list.\n"
|
96 |
+
]
|
97 |
+
},
|
98 |
+
{
|
99 |
+
"cell_type": "code",
|
100 |
+
"execution_count": 4,
|
101 |
+
"metadata": {},
|
102 |
+
"outputs": [
|
103 |
+
{
|
104 |
+
"data": {
|
105 |
+
"text/plain": [
|
106 |
+
"1"
|
107 |
+
]
|
108 |
+
},
|
109 |
+
"execution_count": 4,
|
110 |
+
"metadata": {},
|
111 |
+
"output_type": "execute_result"
|
112 |
+
}
|
113 |
+
],
|
114 |
+
"source": [
|
115 |
+
"text_loader = TextFileLoader(\"data/KingLear.txt\")\n",
|
116 |
+
"documents = text_loader.load_documents()\n",
|
117 |
+
"len(documents)"
|
118 |
+
]
|
119 |
+
},
|
120 |
+
{
|
121 |
+
"cell_type": "code",
|
122 |
+
"execution_count": 5,
|
123 |
+
"metadata": {},
|
124 |
+
"outputs": [
|
125 |
+
{
|
126 |
+
"name": "stdout",
|
127 |
+
"output_type": "stream",
|
128 |
+
"text": [
|
129 |
+
"ACT I\n",
|
130 |
+
"SCENE I. King Lear's palace.\n",
|
131 |
+
"Enter KENT, GLOUCESTER, and EDMUND\n",
|
132 |
+
"KENT\n",
|
133 |
+
"I thought the king had m\n"
|
134 |
+
]
|
135 |
+
}
|
136 |
+
],
|
137 |
+
"source": [
|
138 |
+
"print(documents[0][:100])"
|
139 |
+
]
|
140 |
+
},
|
141 |
+
{
|
142 |
+
"cell_type": "markdown",
|
143 |
+
"metadata": {},
|
144 |
+
"source": [
|
145 |
+
"### Splitting Text Into Chunks\n",
|
146 |
+
"\n",
|
147 |
+
"As we can see, there is one document - and it's the entire text of King Lear.\n",
|
148 |
+
"\n",
|
149 |
+
"We'll want to chunk the document into smaller parts so it's easier to pass the most relevant snippets to the LLM. \n",
|
150 |
+
"\n",
|
151 |
+
"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",
|
152 |
+
"\n",
|
153 |
+
"For this toy example, we'll just split blindly on length. \n",
|
154 |
+
"\n",
|
155 |
+
">There's an opportunity to clear up some terminology here, for this course we will be stick to the following: \n",
|
156 |
+
">\n",
|
157 |
+
">- \"source documents\" : The `.txt`, `.pdf`, `.html`, ..., files that make up the files and information we start with in its raw format\n",
|
158 |
+
">- \"document(s)\" : single (or more) text object(s)\n",
|
159 |
+
">- \"corpus\" : the combination of all of our documents"
|
160 |
+
]
|
161 |
+
},
|
162 |
+
{
|
163 |
+
"cell_type": "markdown",
|
164 |
+
"metadata": {},
|
165 |
+
"source": [
|
166 |
+
"Let's take a peek visually at what we're doing here - and why it might be useful:\n",
|
167 |
+
"\n",
|
168 |
+
"<img src=\"https://i.imgur.com/rtM6Ci6.png\" />"
|
169 |
+
]
|
170 |
+
},
|
171 |
+
{
|
172 |
+
"cell_type": "markdown",
|
173 |
+
"metadata": {},
|
174 |
+
"source": [
|
175 |
+
"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."
|
176 |
+
]
|
177 |
+
},
|
178 |
+
{
|
179 |
+
"cell_type": "code",
|
180 |
+
"execution_count": 6,
|
181 |
+
"metadata": {},
|
182 |
+
"outputs": [
|
183 |
+
{
|
184 |
+
"data": {
|
185 |
+
"text/plain": [
|
186 |
+
"189"
|
187 |
+
]
|
188 |
+
},
|
189 |
+
"execution_count": 6,
|
190 |
+
"metadata": {},
|
191 |
+
"output_type": "execute_result"
|
192 |
+
}
|
193 |
+
],
|
194 |
+
"source": [
|
195 |
+
"text_splitter = CharacterTextSplitter()\n",
|
196 |
+
"split_documents = text_splitter.split_texts(documents)\n",
|
197 |
+
"len(split_documents)"
|
198 |
+
]
|
199 |
+
},
|
200 |
+
{
|
201 |
+
"cell_type": "markdown",
|
202 |
+
"metadata": {},
|
203 |
+
"source": [
|
204 |
+
"Let's take a look at some of the documents we've managed to split."
|
205 |
+
]
|
206 |
+
},
|
207 |
+
{
|
208 |
+
"cell_type": "code",
|
209 |
+
"execution_count": 7,
|
210 |
+
"metadata": {},
|
211 |
+
"outputs": [
|
212 |
+
{
|
213 |
+
"data": {
|
214 |
+
"text/plain": [
|
215 |
+
"[\"\\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\"]"
|
216 |
+
]
|
217 |
+
},
|
218 |
+
"execution_count": 7,
|
219 |
+
"metadata": {},
|
220 |
+
"output_type": "execute_result"
|
221 |
+
}
|
222 |
+
],
|
223 |
+
"source": [
|
224 |
+
"split_documents[0:1]"
|
225 |
+
]
|
226 |
+
},
|
227 |
+
{
|
228 |
+
"cell_type": "markdown",
|
229 |
+
"metadata": {},
|
230 |
+
"source": [
|
231 |
+
"### Embeddings and Vectors\n",
|
232 |
+
"\n",
|
233 |
+
"Next, we have to convert our corpus into a \"machine readable\" format. \n",
|
234 |
+
"\n",
|
235 |
+
"Loosely, this means turning the text into numbers. \n",
|
236 |
+
"\n",
|
237 |
+
"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",
|
238 |
+
"\n",
|
239 |
+
"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."
|
240 |
+
]
|
241 |
+
},
|
242 |
+
{
|
243 |
+
"cell_type": "markdown",
|
244 |
+
"metadata": {},
|
245 |
+
"source": [
|
246 |
+
"While this is all baked into 1 call - let's look at some of the code that powers this process:\n",
|
247 |
+
"\n",
|
248 |
+
"Let's look at our `VectorDatabase().__init__()`:\n",
|
249 |
+
"\n",
|
250 |
+
"```python\n",
|
251 |
+
"def __init__(self, embedding_model: EmbeddingModel = None):\n",
|
252 |
+
" self.vectors = defaultdict(np.array)\n",
|
253 |
+
" self.embedding_model = embedding_model or EmbeddingModel()\n",
|
254 |
+
"```\n",
|
255 |
+
"\n",
|
256 |
+
"As you can see - our vectors are merely stored as a dictionary of `np.array` objects.\n",
|
257 |
+
"\n",
|
258 |
+
"Secondly, our `VectorDatabase()` has a default `EmbeddingModel()` which is a wrapper for OpenAI's `text-embedding-ada-002` model. \n",
|
259 |
+
"\n",
|
260 |
+
"> **Quick Info About `text-embedding-ada-002`**:\n",
|
261 |
+
"> - It has a context window of **8192** tokens\n",
|
262 |
+
"> - It returns vectors with dimension **1536**"
|
263 |
+
]
|
264 |
+
},
|
265 |
+
{
|
266 |
+
"cell_type": "code",
|
267 |
+
"execution_count": 8,
|
268 |
+
"metadata": {},
|
269 |
+
"outputs": [],
|
270 |
+
"source": [
|
271 |
+
"import os\n",
|
272 |
+
"import openai\n",
|
273 |
+
"from getpass import getpass\n",
|
274 |
+
"\n",
|
275 |
+
"openai.api_key = getpass(\"OpenAI API Key: \")\n",
|
276 |
+
"os.environ[\"OPENAI_API_KEY\"] = openai.api_key"
|
277 |
+
]
|
278 |
+
},
|
279 |
+
{
|
280 |
+
"cell_type": "markdown",
|
281 |
+
"metadata": {},
|
282 |
+
"source": [
|
283 |
+
"We can call the `async_get_embeddings` method of our `EmbeddingModel()` on a list of `str` and receive a list of `float` back!\n",
|
284 |
+
"\n",
|
285 |
+
"```python\n",
|
286 |
+
"async def async_get_embeddings(self, list_of_text: List[str]) -> List[List[float]]:\n",
|
287 |
+
" return await aget_embeddings(\n",
|
288 |
+
" list_of_text=list_of_text, engine=self.embeddings_model_name\n",
|
289 |
+
" )\n",
|
290 |
+
"```"
|
291 |
+
]
|
292 |
+
},
|
293 |
+
{
|
294 |
+
"cell_type": "markdown",
|
295 |
+
"metadata": {},
|
296 |
+
"source": [
|
297 |
+
"We cast those to `np.array` when we build our `VectorDatabase()`:\n",
|
298 |
+
"\n",
|
299 |
+
"```python\n",
|
300 |
+
"async def abuild_from_list(self, list_of_text: List[str]) -> \"VectorDatabase\":\n",
|
301 |
+
" embeddings = await self.embedding_model.async_get_embeddings(list_of_text)\n",
|
302 |
+
" for text, embedding in zip(list_of_text, embeddings):\n",
|
303 |
+
" self.insert(text, np.array(embedding))\n",
|
304 |
+
" return self\n",
|
305 |
+
"```\n",
|
306 |
+
"\n",
|
307 |
+
"And that's all we need to do!"
|
308 |
+
]
|
309 |
+
},
|
310 |
+
{
|
311 |
+
"cell_type": "code",
|
312 |
+
"execution_count": 9,
|
313 |
+
"metadata": {},
|
314 |
+
"outputs": [],
|
315 |
+
"source": [
|
316 |
+
"vector_db = VectorDatabase()\n",
|
317 |
+
"vector_db = asyncio.run(vector_db.abuild_from_list(split_documents))"
|
318 |
+
]
|
319 |
+
},
|
320 |
+
{
|
321 |
+
"cell_type": "markdown",
|
322 |
+
"metadata": {},
|
323 |
+
"source": [
|
324 |
+
"So, to review what we've done so far in natural language:\n",
|
325 |
+
"\n",
|
326 |
+
"1. We load source documents\n",
|
327 |
+
"2. We split those source documents into smaller chunks (documents)\n",
|
328 |
+
"3. We send each of those documents to the `text-embedding-ada-002` OpenAI API endpoint\n",
|
329 |
+
"4. We store each of the text representations with the vector representations as keys/values in a dictionary"
|
330 |
+
]
|
331 |
+
},
|
332 |
+
{
|
333 |
+
"cell_type": "markdown",
|
334 |
+
"metadata": {},
|
335 |
+
"source": [
|
336 |
+
"### Semantic Similarity\n",
|
337 |
+
"\n",
|
338 |
+
"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",
|
339 |
+
"\n",
|
340 |
+
"We're going to use the following process to achieve this in our toy example:\n",
|
341 |
+
"\n",
|
342 |
+
"1. We need to embed our query with the same `EmbeddingModel()` as we used to construct our `VectorDatabase()`\n",
|
343 |
+
"2. We loop through every vector in our `VectorDatabase()` and use a distance measure to compare how related they are\n",
|
344 |
+
"3. We return a list of the top `k` closest vectors, with their text representations\n",
|
345 |
+
"\n",
|
346 |
+
"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",
|
347 |
+
"\n",
|
348 |
+
"> 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",
|
349 |
+
"\n",
|
350 |
+
"> 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)"
|
351 |
+
]
|
352 |
+
},
|
353 |
+
{
|
354 |
+
"cell_type": "code",
|
355 |
+
"execution_count": 10,
|
356 |
+
"metadata": {},
|
357 |
+
"outputs": [
|
358 |
+
{
|
359 |
+
"data": {
|
360 |
+
"text/plain": [
|
361 |
+
"[(\"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",
|
362 |
+
" 0.8210900574380693),\n",
|
363 |
+
" (\"her way,\\nThe news is not so tart.--I'll read, and answer.\\nExit\\n\\nALBANY\\nWhere was his son when they did take his eyes?\\nMessenger\\nCome with my lady hither.\\nALBANY\\nHe is not here.\\nMessenger\\nNo, my good lord; I met him back again.\\nALBANY\\nKnows he the wickedness?\\nMessenger\\nAy, my good lord; 'twas he inform'd against him;\\nAnd quit the house on purpose, that their punishment\\nMight have the freer course.\\nALBANY\\nGloucester, I live\\nTo thank thee for the love thou show'dst the king,\\nAnd to revenge thine eyes. Come hither, friend:\\nTell me what more thou know'st.\\nExeunt\\n\\nSCENE III. The French camp near Dover.\\nEnter KENT and a Gentleman\\nKENT\\nWhy the King of France is so suddenly gone back\\nknow you the reason?\\nGentleman\\nSomething he left imperfect in the\\nstate, which since his coming forth is thought\\nof; which imports to the kingdom so much\\nfear and danger, that his personal return was\\nmost required and necessary.\\nKENT\\nWho hath he left behind him general?\\nGentleman\\nThe Marshal of France, Monsieur La \",\n",
|
364 |
+
" 0.8195972501864015),\n",
|
365 |
+
" (\",\\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",
|
366 |
+
" 0.8179890218803361)]"
|
367 |
+
]
|
368 |
+
},
|
369 |
+
"execution_count": 10,
|
370 |
+
"metadata": {},
|
371 |
+
"output_type": "execute_result"
|
372 |
+
}
|
373 |
+
],
|
374 |
+
"source": [
|
375 |
+
"vector_db.search_by_text(\"Your servant Kent. Where is your servant Caius?\", k=3)"
|
376 |
+
]
|
377 |
+
},
|
378 |
+
{
|
379 |
+
"cell_type": "markdown",
|
380 |
+
"metadata": {},
|
381 |
+
"source": [
|
382 |
+
"# Prompts\n",
|
383 |
+
"\n",
|
384 |
+
"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",
|
385 |
+
"\n",
|
386 |
+
"In this notebook, we're going to rely on the idea of \"zero-shot in-context learning\".\n",
|
387 |
+
"\n",
|
388 |
+
"This is a lot of words to say: \"We will ask it to perform our desired task in the prompt, and provide no examples.\""
|
389 |
+
]
|
390 |
+
},
|
391 |
+
{
|
392 |
+
"cell_type": "markdown",
|
393 |
+
"metadata": {},
|
394 |
+
"source": [
|
395 |
+
"### XYZRolePrompt\n",
|
396 |
+
"\n",
|
397 |
+
"Before we do that, let's stop and think a bit about how OpenAI's chat models work. \n",
|
398 |
+
"\n",
|
399 |
+
"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",
|
400 |
+
"\n",
|
401 |
+
"There are three roles, and they function as follows (taken directly from [OpenAI](https://platform.openai.com/docs/guides/gpt/chat-completions-api)): \n",
|
402 |
+
"\n",
|
403 |
+
"- `{\"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",
|
404 |
+
"- `{\"role\" : \"user\"}` : The user messages provide requests or comments for the assistant to respond to.\n",
|
405 |
+
"- `{\"role\" : \"assistant\"}` : Assistant messages store previous assistant responses, but can also be written by you to give examples of desired behavior.\n",
|
406 |
+
"\n",
|
407 |
+
"The main idea is this: \n",
|
408 |
+
"\n",
|
409 |
+
"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",
|
410 |
+
"2. Then, you can provide a few examples in the form of \"assistant\"/\"user\" pairs\n",
|
411 |
+
"3. Then, you prompt the model with the true \"user\" message.\n",
|
412 |
+
"\n",
|
413 |
+
"In this example, we'll be forgoing the 2nd step for simplicities sake."
|
414 |
+
]
|
415 |
+
},
|
416 |
+
{
|
417 |
+
"cell_type": "markdown",
|
418 |
+
"metadata": {},
|
419 |
+
"source": [
|
420 |
+
"#### Utility Functions\n",
|
421 |
+
"\n",
|
422 |
+
"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!"
|
423 |
+
]
|
424 |
+
},
|
425 |
+
{
|
426 |
+
"cell_type": "markdown",
|
427 |
+
"metadata": {},
|
428 |
+
"source": [
|
429 |
+
"##### XYZRolePrompt"
|
430 |
+
]
|
431 |
+
},
|
432 |
+
{
|
433 |
+
"cell_type": "markdown",
|
434 |
+
"metadata": {},
|
435 |
+
"source": [
|
436 |
+
"Here we have our `system`, `user`, and `assistant` role prompts. \n",
|
437 |
+
"\n",
|
438 |
+
"Let's take a peek at what they look like:\n",
|
439 |
+
"\n",
|
440 |
+
"```python\n",
|
441 |
+
"class BasePrompt:\n",
|
442 |
+
" def __init__(self, prompt):\n",
|
443 |
+
" \"\"\"\n",
|
444 |
+
" Initializes the BasePrompt object with a prompt template.\n",
|
445 |
+
"\n",
|
446 |
+
" :param prompt: A string that can contain placeholders within curly braces\n",
|
447 |
+
" \"\"\"\n",
|
448 |
+
" self.prompt = prompt\n",
|
449 |
+
" self._pattern = re.compile(r\"\\{([^}]+)\\}\")\n",
|
450 |
+
"\n",
|
451 |
+
" def format_prompt(self, **kwargs):\n",
|
452 |
+
" \"\"\"\n",
|
453 |
+
" Formats the prompt string using the keyword arguments provided.\n",
|
454 |
+
"\n",
|
455 |
+
" :param kwargs: The values to substitute into the prompt string\n",
|
456 |
+
" :return: The formatted prompt string\n",
|
457 |
+
" \"\"\"\n",
|
458 |
+
" matches = self._pattern.findall(self.prompt)\n",
|
459 |
+
" return self.prompt.format(**{match: kwargs.get(match, \"\") for match in matches})\n",
|
460 |
+
"\n",
|
461 |
+
" def get_input_variables(self):\n",
|
462 |
+
" \"\"\"\n",
|
463 |
+
" Gets the list of input variable names from the prompt string.\n",
|
464 |
+
"\n",
|
465 |
+
" :return: List of input variable names\n",
|
466 |
+
" \"\"\"\n",
|
467 |
+
" return self._pattern.findall(self.prompt)\n",
|
468 |
+
"```\n",
|
469 |
+
"\n",
|
470 |
+
"Then we have our `RolePrompt` which laser focuses us on the role pattern found in most API endpoints for LLMs.\n",
|
471 |
+
"\n",
|
472 |
+
"```python\n",
|
473 |
+
"class RolePrompt(BasePrompt):\n",
|
474 |
+
" def __init__(self, prompt, role: str):\n",
|
475 |
+
" \"\"\"\n",
|
476 |
+
" Initializes the RolePrompt object with a prompt template and a role.\n",
|
477 |
+
"\n",
|
478 |
+
" :param prompt: A string that can contain placeholders within curly braces\n",
|
479 |
+
" :param role: The role for the message ('system', 'user', or 'assistant')\n",
|
480 |
+
" \"\"\"\n",
|
481 |
+
" super().__init__(prompt)\n",
|
482 |
+
" self.role = role\n",
|
483 |
+
"\n",
|
484 |
+
" def create_message(self, **kwargs):\n",
|
485 |
+
" \"\"\"\n",
|
486 |
+
" Creates a message dictionary with a role and a formatted message.\n",
|
487 |
+
"\n",
|
488 |
+
" :param kwargs: The values to substitute into the prompt string\n",
|
489 |
+
" :return: Dictionary containing the role and the formatted message\n",
|
490 |
+
" \"\"\"\n",
|
491 |
+
" return {\"role\": self.role, \"content\": self.format_prompt(**kwargs)}\n",
|
492 |
+
"```\n",
|
493 |
+
"\n",
|
494 |
+
"We'll look at how the `SystemRolePrompt` is constructed to get a better idea of how that extension works:\n",
|
495 |
+
"\n",
|
496 |
+
"```python\n",
|
497 |
+
"class SystemRolePrompt(RolePrompt):\n",
|
498 |
+
" def __init__(self, prompt: str):\n",
|
499 |
+
" super().__init__(prompt, \"system\")\n",
|
500 |
+
"```\n",
|
501 |
+
"\n",
|
502 |
+
"That pattern is repeated for our `UserRolePrompt` and our `AssistantRolePrompt` as well."
|
503 |
+
]
|
504 |
+
},
|
505 |
+
{
|
506 |
+
"cell_type": "markdown",
|
507 |
+
"metadata": {},
|
508 |
+
"source": [
|
509 |
+
"##### ChatOpenAI"
|
510 |
+
]
|
511 |
+
},
|
512 |
+
{
|
513 |
+
"cell_type": "markdown",
|
514 |
+
"metadata": {},
|
515 |
+
"source": [
|
516 |
+
"Next we have our model, which is converted to a format analagous to libraries like LangChain and LlamaIndex.\n",
|
517 |
+
"\n",
|
518 |
+
"Let's take a peek at how that is constructed:\n",
|
519 |
+
"\n",
|
520 |
+
"```python\n",
|
521 |
+
"class ChatOpenAI:\n",
|
522 |
+
" def __init__(self, model_name: str = \"gpt-3.5-turbo\"):\n",
|
523 |
+
" self.model_name = model_name\n",
|
524 |
+
" self.openai_api_key = os.getenv(\"OPENAI_API_KEY\")\n",
|
525 |
+
" if self.openai_api_key is None:\n",
|
526 |
+
" raise ValueError(\"OPENAI_API_KEY is not set\")\n",
|
527 |
+
"\n",
|
528 |
+
" def run(self, messages, text_only: bool = True):\n",
|
529 |
+
" if not isinstance(messages, list):\n",
|
530 |
+
" raise ValueError(\"messages must be a list\")\n",
|
531 |
+
"\n",
|
532 |
+
" openai.api_key = self.openai_api_key\n",
|
533 |
+
" response = openai.ChatCompletion.create(\n",
|
534 |
+
" model=self.model_name, messages=messages\n",
|
535 |
+
" )\n",
|
536 |
+
"\n",
|
537 |
+
" if text_only:\n",
|
538 |
+
" return response.choices[0].message.content\n",
|
539 |
+
"\n",
|
540 |
+
" return response\n",
|
541 |
+
"```"
|
542 |
+
]
|
543 |
+
},
|
544 |
+
{
|
545 |
+
"cell_type": "markdown",
|
546 |
+
"metadata": {},
|
547 |
+
"source": [
|
548 |
+
"### Creating and Prompting OpenAI's `gpt-3.5-turbo`!\n",
|
549 |
+
"\n",
|
550 |
+
"Let's tie all these together and use it to prompt `gpt-3.5-turbo`!"
|
551 |
+
]
|
552 |
+
},
|
553 |
+
{
|
554 |
+
"cell_type": "code",
|
555 |
+
"execution_count": 11,
|
556 |
+
"metadata": {},
|
557 |
+
"outputs": [],
|
558 |
+
"source": [
|
559 |
+
"from aimakerspace.openai_utils.prompts import (\n",
|
560 |
+
" UserRolePrompt,\n",
|
561 |
+
" SystemRolePrompt,\n",
|
562 |
+
" AssistantRolePrompt,\n",
|
563 |
+
")\n",
|
564 |
+
"\n",
|
565 |
+
"from aimakerspace.openai_utils.chatmodel import ChatOpenAI\n",
|
566 |
+
"\n",
|
567 |
+
"chat_openai = ChatOpenAI()\n",
|
568 |
+
"user_prompt_template = \"{content}\"\n",
|
569 |
+
"user_role_prompt = UserRolePrompt(user_prompt_template)\n",
|
570 |
+
"system_prompt_template = (\n",
|
571 |
+
" \"You are an expert in {expertise}, you always answer in a kind way.\"\n",
|
572 |
+
")\n",
|
573 |
+
"system_role_prompt = SystemRolePrompt(system_prompt_template)\n",
|
574 |
+
"\n",
|
575 |
+
"messages = [\n",
|
576 |
+
" user_role_prompt.create_message(\n",
|
577 |
+
" content=\"What is the best way to write a loop?\"\n",
|
578 |
+
" ),\n",
|
579 |
+
" system_role_prompt.create_message(expertise=\"Python\"),\n",
|
580 |
+
"]\n",
|
581 |
+
"\n",
|
582 |
+
"response = chat_openai.run(messages)"
|
583 |
+
]
|
584 |
+
},
|
585 |
+
{
|
586 |
+
"cell_type": "code",
|
587 |
+
"execution_count": 12,
|
588 |
+
"metadata": {},
|
589 |
+
"outputs": [
|
590 |
+
{
|
591 |
+
"name": "stdout",
|
592 |
+
"output_type": "stream",
|
593 |
+
"text": [
|
594 |
+
"There is no one \"best\" way to write a loop, as it depends on the specific requirements and context of your program. However, I can provide some general tips to help you write efficient and effective loops:\n",
|
595 |
+
"\n",
|
596 |
+
"1. Choose the appropriate loop construct: In most cases, the `for` and `while` loops are the commonly used constructs. The choice depends on whether you know the number of iterations in advance (`for` loop) or if the loop needs to continue until a certain condition is met (`while` loop).\n",
|
597 |
+
"\n",
|
598 |
+
"2. Define the loop condition carefully: When using a `while` loop, ensure that the condition specifies when the loop should terminate. Make sure to increment or decrement any necessary variables within the loop to avoid infinite loops.\n",
|
599 |
+
"\n",
|
600 |
+
"3. Keep the loop body concise: To improve readability, only include essential code within the loop body. If possible, move complex calculations or repetitive operations outside the loop.\n",
|
601 |
+
"\n",
|
602 |
+
"4. Use loop control statements wisely: Utilize loop control statements like `break` and `continue` when necessary. `break` allows you to exit the loop prematurely, while `continue` lets you skip the remaining code within a particular iteration.\n",
|
603 |
+
"\n",
|
604 |
+
"5. Consider using built-in functions: Python provides several built-in functions like `range()` and `enumerate()` that can simplify loop iterations. They offer convenient ways to generate sequences or access indices and values simultaneously.\n",
|
605 |
+
"\n",
|
606 |
+
"6. Optimize performance when needed: If efficiency is crucial, consider using techniques such as list comprehension or generator expressions. These approaches can often provide faster execution compared to traditional loops.\n",
|
607 |
+
"\n",
|
608 |
+
"7. Ensure code clarity and maintainability: Write your loops in a way that is easy to understand and maintain. Use meaningful variable names and add comments when necessary to clarify the purpose and logic of the loop.\n",
|
609 |
+
"\n",
|
610 |
+
"Remember, the best way to write a loop depends on the specific requirements of your program, so choose an approach that suits your needs and improves the overall readability and efficiency of your code.\n"
|
611 |
+
]
|
612 |
+
}
|
613 |
+
],
|
614 |
+
"source": [
|
615 |
+
"print(response)"
|
616 |
+
]
|
617 |
+
},
|
618 |
+
{
|
619 |
+
"cell_type": "markdown",
|
620 |
+
"metadata": {},
|
621 |
+
"source": [
|
622 |
+
"### Retrieval Augmented Question Answering Prompt\n",
|
623 |
+
"\n",
|
624 |
+
"Now we can create a RAQA prompt - which will help our system behave in a way that makes sense!\n",
|
625 |
+
"\n",
|
626 |
+
"There is much you could do here, many tweaks and improvements to be made!"
|
627 |
+
]
|
628 |
+
},
|
629 |
+
{
|
630 |
+
"cell_type": "code",
|
631 |
+
"execution_count": 13,
|
632 |
+
"metadata": {},
|
633 |
+
"outputs": [],
|
634 |
+
"source": [
|
635 |
+
"RAQA_PROMPT_TEMPLATE = \"\"\"\n",
|
636 |
+
"Use the provided context to answer the user's query. \n",
|
637 |
+
"\n",
|
638 |
+
"You may not answer the user's query unless there is specific context in the following text.\n",
|
639 |
+
"\n",
|
640 |
+
"If you do not know the answer, or cannot answer, please respond with \"I don't know\".\n",
|
641 |
+
"\n",
|
642 |
+
"Context:\n",
|
643 |
+
"{context}\n",
|
644 |
+
"\"\"\"\n",
|
645 |
+
"\n",
|
646 |
+
"raqa_prompt = SystemRolePrompt(RAQA_PROMPT_TEMPLATE)\n",
|
647 |
+
"\n",
|
648 |
+
"USER_PROMPT_TEMPLATE = \"\"\"\n",
|
649 |
+
"User Query:\n",
|
650 |
+
"{user_query}\n",
|
651 |
+
"\"\"\"\n",
|
652 |
+
"\n",
|
653 |
+
"user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)\n",
|
654 |
+
"\n",
|
655 |
+
"class RetrievalAugmentedQAPipeline:\n",
|
656 |
+
" def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:\n",
|
657 |
+
" self.llm = llm\n",
|
658 |
+
" self.vector_db_retriever = vector_db_retriever\n",
|
659 |
+
"\n",
|
660 |
+
" def run_pipeline(self, user_query: str) -> str:\n",
|
661 |
+
" context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
|
662 |
+
" \n",
|
663 |
+
" context_prompt = \"\"\n",
|
664 |
+
" for context in context_list:\n",
|
665 |
+
" context_prompt += context[0] + \"\\n\"\n",
|
666 |
+
"\n",
|
667 |
+
" formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)\n",
|
668 |
+
"\n",
|
669 |
+
" formatted_user_prompt = user_prompt.create_message(user_query=user_query)\n",
|
670 |
+
" \n",
|
671 |
+
" return self.llm.run([formatted_system_prompt, formatted_user_prompt])"
|
672 |
+
]
|
673 |
+
},
|
674 |
+
{
|
675 |
+
"cell_type": "code",
|
676 |
+
"execution_count": 14,
|
677 |
+
"metadata": {},
|
678 |
+
"outputs": [],
|
679 |
+
"source": [
|
680 |
+
"retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
|
681 |
+
" vector_db_retriever=vector_db,\n",
|
682 |
+
" llm=chat_openai\n",
|
683 |
+
")"
|
684 |
+
]
|
685 |
+
},
|
686 |
+
{
|
687 |
+
"cell_type": "code",
|
688 |
+
"execution_count": 15,
|
689 |
+
"metadata": {},
|
690 |
+
"outputs": [
|
691 |
+
{
|
692 |
+
"data": {
|
693 |
+
"text/plain": [
|
694 |
+
"'King Lear is a character in the play \"King Lear\" by William Shakespeare. He is a king who, in his old age, decides to divide his kingdom among his three daughters based on how much they profess to love him. However, he soon realizes that his decision was a mistake, and he descends into madness as his family turns against him.'"
|
695 |
+
]
|
696 |
+
},
|
697 |
+
"execution_count": 15,
|
698 |
+
"metadata": {},
|
699 |
+
"output_type": "execute_result"
|
700 |
+
}
|
701 |
+
],
|
702 |
+
"source": [
|
703 |
+
"retrieval_augmented_qa_pipeline.run_pipeline(\"Who is King Lear?\")"
|
704 |
+
]
|
705 |
+
},
|
706 |
+
{
|
707 |
+
"cell_type": "markdown",
|
708 |
+
"metadata": {},
|
709 |
+
"source": [
|
710 |
+
"### Visibility Tooling\n",
|
711 |
+
"\n",
|
712 |
+
"This is great, but what if we wanted to add some visibility to our pipeline?\n",
|
713 |
+
"\n",
|
714 |
+
"Let's use Weights and Biases as a visibility tool!\n",
|
715 |
+
"\n",
|
716 |
+
"The first thing we'll need to do is create a Weights and Biases account and get an API key. \n",
|
717 |
+
"\n",
|
718 |
+
"You can follow the process outlined [here](https://docs.wandb.ai/quickstart) to do exactly that!"
|
719 |
+
]
|
720 |
+
},
|
721 |
+
{
|
722 |
+
"cell_type": "markdown",
|
723 |
+
"metadata": {},
|
724 |
+
"source": [
|
725 |
+
"Now we can get the Weights and Biases dependency and add our key to our env. to begin!"
|
726 |
+
]
|
727 |
+
},
|
728 |
+
{
|
729 |
+
"cell_type": "code",
|
730 |
+
"execution_count": 16,
|
731 |
+
"metadata": {},
|
732 |
+
"outputs": [],
|
733 |
+
"source": [
|
734 |
+
"!pip install -q -U wandb"
|
735 |
+
]
|
736 |
+
},
|
737 |
+
{
|
738 |
+
"cell_type": "code",
|
739 |
+
"execution_count": 17,
|
740 |
+
"metadata": {},
|
741 |
+
"outputs": [],
|
742 |
+
"source": [
|
743 |
+
"wandb_key = getpass(\"Weights and Biases API Key: \")\n",
|
744 |
+
"os.environ[\"WANDB_API_KEY\"] = wandb_key"
|
745 |
+
]
|
746 |
+
},
|
747 |
+
{
|
748 |
+
"cell_type": "code",
|
749 |
+
"execution_count": null,
|
750 |
+
"metadata": {},
|
751 |
+
"outputs": [],
|
752 |
+
"source": [
|
753 |
+
"import wandb\n",
|
754 |
+
"\n",
|
755 |
+
"os.environ[\"WANDB_NOTEBOOK_NAME\"] = \"Python RAQA Example.ipynb\"\n",
|
756 |
+
"wandb.init(project=\"Visibility Example\")"
|
757 |
+
]
|
758 |
+
},
|
759 |
+
{
|
760 |
+
"cell_type": "markdown",
|
761 |
+
"metadata": {},
|
762 |
+
"source": [
|
763 |
+
"Now we can integrate Weights and Biases into our `RetrievalAugmentedQAPipeline`.\n",
|
764 |
+
"\n",
|
765 |
+
"```python\n",
|
766 |
+
"if self.wandb_project:\n",
|
767 |
+
" root_span = Trace(\n",
|
768 |
+
" name=\"root_span\",\n",
|
769 |
+
" kind=\"llm\",\n",
|
770 |
+
" status_code=status,\n",
|
771 |
+
" status_message=status_message,\n",
|
772 |
+
" start_time_ms=start_time,\n",
|
773 |
+
" end_time_ms=end_time,\n",
|
774 |
+
" metadata={\n",
|
775 |
+
" \"token_usage\" : token_usage\n",
|
776 |
+
" },\n",
|
777 |
+
" inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
|
778 |
+
" outputs= {\"response\" : response_text}\n",
|
779 |
+
" )\n",
|
780 |
+
"\n",
|
781 |
+
" root_span.log(name=\"openai_trace\")\n",
|
782 |
+
"```\n",
|
783 |
+
"\n",
|
784 |
+
"The main things to consider here are how to populate the various fields to make sure we're tracking useful information. \n",
|
785 |
+
"\n",
|
786 |
+
"We'll use the `text_only` flag to ensure we can get detailed information about our LLM call!\n",
|
787 |
+
"\n",
|
788 |
+
"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)"
|
789 |
+
]
|
790 |
+
},
|
791 |
+
{
|
792 |
+
"cell_type": "code",
|
793 |
+
"execution_count": 19,
|
794 |
+
"metadata": {},
|
795 |
+
"outputs": [],
|
796 |
+
"source": [
|
797 |
+
"import datetime\n",
|
798 |
+
"from wandb.sdk.data_types.trace_tree import Trace\n",
|
799 |
+
"\n",
|
800 |
+
"class RetrievalAugmentedQAPipeline:\n",
|
801 |
+
" def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase, wandb_project = None) -> None:\n",
|
802 |
+
" self.llm = llm\n",
|
803 |
+
" self.vector_db_retriever = vector_db_retriever\n",
|
804 |
+
" self.wandb_project = wandb_project\n",
|
805 |
+
"\n",
|
806 |
+
" def run_pipeline(self, user_query: str) -> str:\n",
|
807 |
+
" context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
|
808 |
+
" \n",
|
809 |
+
" context_prompt = \"\"\n",
|
810 |
+
" for context in context_list:\n",
|
811 |
+
" context_prompt += context[0] + \"\\n\"\n",
|
812 |
+
"\n",
|
813 |
+
" formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)\n",
|
814 |
+
"\n",
|
815 |
+
" formatted_user_prompt = user_prompt.create_message(user_query=user_query)\n",
|
816 |
+
"\n",
|
817 |
+
" \n",
|
818 |
+
" start_time = datetime.datetime.now().timestamp() * 1000\n",
|
819 |
+
"\n",
|
820 |
+
" try:\n",
|
821 |
+
" openai_response = self.llm.run([formatted_system_prompt, formatted_user_prompt], text_only=False)\n",
|
822 |
+
" end_time = datetime.datetime.now().timestamp() * 1000\n",
|
823 |
+
" status = \"success\"\n",
|
824 |
+
" status_message = (None, )\n",
|
825 |
+
" response_text = openai_response.choices[0].message.content\n",
|
826 |
+
" token_usage = openai_response[\"usage\"].to_dict()\n",
|
827 |
+
" model = openai_response[\"model\"]\n",
|
828 |
+
"\n",
|
829 |
+
" except Exception as e:\n",
|
830 |
+
" end_time = datetime.datetime.now().timestamp() * 1000\n",
|
831 |
+
" status = \"error\"\n",
|
832 |
+
" status_message = str(e)\n",
|
833 |
+
" response_text = \"\"\n",
|
834 |
+
" token_usage = {}\n",
|
835 |
+
" model = \"\"\n",
|
836 |
+
"\n",
|
837 |
+
" if self.wandb_project:\n",
|
838 |
+
" root_span = Trace(\n",
|
839 |
+
" name=\"root_span\",\n",
|
840 |
+
" kind=\"llm\",\n",
|
841 |
+
" status_code=status,\n",
|
842 |
+
" status_message=status_message,\n",
|
843 |
+
" start_time_ms=start_time,\n",
|
844 |
+
" end_time_ms=end_time,\n",
|
845 |
+
" metadata={\n",
|
846 |
+
" \"token_usage\" : token_usage,\n",
|
847 |
+
" \"model_name\" : model\n",
|
848 |
+
" },\n",
|
849 |
+
" inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
|
850 |
+
" outputs= {\"response\" : response_text}\n",
|
851 |
+
" )\n",
|
852 |
+
"\n",
|
853 |
+
" root_span.log(name=\"openai_trace\")\n",
|
854 |
+
" \n",
|
855 |
+
" return response_text if response_text else \"We ran into an error. Please try again later. Full Error Message: \" + status_message"
|
856 |
+
]
|
857 |
+
},
|
858 |
+
{
|
859 |
+
"cell_type": "code",
|
860 |
+
"execution_count": 20,
|
861 |
+
"metadata": {},
|
862 |
+
"outputs": [],
|
863 |
+
"source": [
|
864 |
+
"retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
|
865 |
+
" vector_db_retriever=vector_db,\n",
|
866 |
+
" llm=chat_openai,\n",
|
867 |
+
" wandb_project=\"LLM Visibility Example\"\n",
|
868 |
+
")"
|
869 |
+
]
|
870 |
+
},
|
871 |
+
{
|
872 |
+
"cell_type": "code",
|
873 |
+
"execution_count": 21,
|
874 |
+
"metadata": {},
|
875 |
+
"outputs": [
|
876 |
+
{
|
877 |
+
"data": {
|
878 |
+
"text/plain": [
|
879 |
+
"\"I don't know.\""
|
880 |
+
]
|
881 |
+
},
|
882 |
+
"execution_count": 21,
|
883 |
+
"metadata": {},
|
884 |
+
"output_type": "execute_result"
|
885 |
+
}
|
886 |
+
],
|
887 |
+
"source": [
|
888 |
+
"retrieval_augmented_qa_pipeline.run_pipeline(\"Who is Batman?\")"
|
889 |
+
]
|
890 |
+
},
|
891 |
+
{
|
892 |
+
"cell_type": "code",
|
893 |
+
"execution_count": 22,
|
894 |
+
"metadata": {},
|
895 |
+
"outputs": [
|
896 |
+
{
|
897 |
+
"data": {
|
898 |
+
"text/plain": [
|
899 |
+
"\"Cordelia dies in King Lear's arms.\""
|
900 |
+
]
|
901 |
+
},
|
902 |
+
"execution_count": 22,
|
903 |
+
"metadata": {},
|
904 |
+
"output_type": "execute_result"
|
905 |
+
}
|
906 |
+
],
|
907 |
+
"source": [
|
908 |
+
"retrieval_augmented_qa_pipeline.run_pipeline(\"What happens to Cordelia?\")"
|
909 |
+
]
|
910 |
+
},
|
911 |
+
{
|
912 |
+
"cell_type": "markdown",
|
913 |
+
"metadata": {},
|
914 |
+
"source": [
|
915 |
+
"Navigate to the Weights and Biases \"run\" link to see how your LLM is performing!\n",
|
916 |
+
"\n",
|
917 |
+
"```\n",
|
918 |
+
"View run at YOUR LINK HERE\n",
|
919 |
+
"```"
|
920 |
+
]
|
921 |
+
},
|
922 |
+
{
|
923 |
+
"cell_type": "markdown",
|
924 |
+
"metadata": {},
|
925 |
+
"source": [
|
926 |
+
"# Conclusion\n",
|
927 |
+
"\n",
|
928 |
+
"In this notebook, we've gone through the steps required to create your own simple RAQA application!\n",
|
929 |
+
"\n",
|
930 |
+
"Please feel free to extend this as much as you'd like. "
|
931 |
+
]
|
932 |
+
},
|
933 |
+
{
|
934 |
+
"cell_type": "markdown",
|
935 |
+
"metadata": {},
|
936 |
+
"source": [
|
937 |
+
"# Bonus Challenges\n",
|
938 |
+
"\n",
|
939 |
+
"Challenge 1: \n",
|
940 |
+
"- Implement a new distance measure\n",
|
941 |
+
"- Implement a more efficient vector search\n",
|
942 |
+
"\n",
|
943 |
+
"Challenge 2: \n",
|
944 |
+
"- Create an external VectorStore that can be run/hosted elsewhere\n",
|
945 |
+
"- Build an adapter for that VectorStore here"
|
946 |
+
]
|
947 |
+
}
|
948 |
+
],
|
949 |
+
"metadata": {
|
950 |
+
"kernelspec": {
|
951 |
+
"display_name": "buildyourownlangchain",
|
952 |
+
"language": "python",
|
953 |
+
"name": "python3"
|
954 |
+
},
|
955 |
+
"language_info": {
|
956 |
+
"codemirror_mode": {
|
957 |
+
"name": "ipython",
|
958 |
+
"version": 3
|
959 |
+
},
|
960 |
+
"file_extension": ".py",
|
961 |
+
"mimetype": "text/x-python",
|
962 |
+
"name": "python",
|
963 |
+
"nbconvert_exporter": "python",
|
964 |
+
"pygments_lexer": "ipython3",
|
965 |
+
"version": "3.9.18"
|
966 |
+
},
|
967 |
+
"orig_nbformat": 4
|
968 |
+
},
|
969 |
+
"nbformat": 4,
|
970 |
+
"nbformat_minor": 2
|
971 |
+
}
|
Dockerfile
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.9
|
2 |
+
RUN useradd -m -u 1000 user
|
3 |
+
USER user
|
4 |
+
ENV HOME=/home/user \
|
5 |
+
PATH=/home/user/.local/bin:$PATH
|
6 |
+
WORKDIR $HOME/app
|
7 |
+
COPY --chown=user .. $HOME/app
|
8 |
+
COPY ./requirements.txt ~/app/requirements.txt
|
9 |
+
RUN pip install -r requirements.txt
|
10 |
+
COPY .. .
|
11 |
+
CMD ["chainlit", "run", "app.py", "--port", "7860"]
|
Python RAQA Example.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
README.md
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: First RAG
|
3 |
+
emoji: 📉
|
4 |
+
colorFrom: pink
|
5 |
+
colorTo: yellow
|
6 |
+
sdk: docker
|
7 |
+
pinned: false
|
8 |
+
---
|
9 |
+
|
10 |
+
|
11 |
+
## <h1 align="center" id="heading">🔍Your First Retrieval Augmented Generation QA Application!</h1>
|
12 |
+
|
13 |
+
|
14 |
+
|
15 |
+
|
16 |
+
|
17 |
+
|
18 |
+
|
19 |
+
|
aimakerspace/__init__.py
ADDED
File without changes
|
aimakerspace/__pycache__/__init__.cpython-311.pyc
ADDED
Binary file (261 Bytes). View file
|
|
aimakerspace/__pycache__/text_utils.cpython-311.pyc
ADDED
Binary file (5.49 kB). View file
|
|
aimakerspace/__pycache__/vectordatabase.cpython-311.pyc
ADDED
Binary file (5.78 kB). View file
|
|
aimakerspace/openai_utils/__init__.py
ADDED
File without changes
|
aimakerspace/openai_utils/__pycache__/__init__.cpython-311.pyc
ADDED
Binary file (274 Bytes). View file
|
|
aimakerspace/openai_utils/__pycache__/chatmodel.cpython-311.pyc
ADDED
Binary file (1.77 kB). View file
|
|
aimakerspace/openai_utils/__pycache__/embedding.cpython-311.pyc
ADDED
Binary file (3.48 kB). View file
|
|
aimakerspace/openai_utils/__pycache__/prompts.cpython-311.pyc
ADDED
Binary file (5.52 kB). View file
|
|
aimakerspace/openai_utils/chatmodel.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import openai
|
2 |
+
from dotenv import load_dotenv
|
3 |
+
import os
|
4 |
+
|
5 |
+
load_dotenv()
|
6 |
+
|
7 |
+
|
8 |
+
class ChatOpenAI:
|
9 |
+
def __init__(self, model_name: str = "gpt-3.5-turbo"):
|
10 |
+
self.model_name = model_name
|
11 |
+
self.openai_api_key = os.getenv("OPENAI_API_KEY")
|
12 |
+
if self.openai_api_key is None:
|
13 |
+
raise ValueError("OPENAI_API_KEY is not set")
|
14 |
+
|
15 |
+
def run(self, messages, text_only: bool = True):
|
16 |
+
if not isinstance(messages, list):
|
17 |
+
raise ValueError("messages must be a list")
|
18 |
+
|
19 |
+
openai.api_key = self.openai_api_key
|
20 |
+
response = openai.ChatCompletion.create(
|
21 |
+
model=self.model_name, messages=messages
|
22 |
+
)
|
23 |
+
|
24 |
+
if text_only:
|
25 |
+
return response.choices[0].message.content
|
26 |
+
|
27 |
+
return response
|
aimakerspace/openai_utils/embedding.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dotenv import load_dotenv
|
2 |
+
from openai.embeddings_utils import (
|
3 |
+
get_embeddings,
|
4 |
+
aget_embeddings,
|
5 |
+
get_embedding,
|
6 |
+
aget_embedding,
|
7 |
+
)
|
8 |
+
import openai
|
9 |
+
from typing import List
|
10 |
+
import os
|
11 |
+
import asyncio
|
12 |
+
|
13 |
+
|
14 |
+
class EmbeddingModel:
|
15 |
+
def __init__(self, embeddings_model_name: str = "text-embedding-ada-002"):
|
16 |
+
load_dotenv()
|
17 |
+
self.openai_api_key = os.getenv("OPENAI_API_KEY")
|
18 |
+
|
19 |
+
if self.openai_api_key is None:
|
20 |
+
raise ValueError(
|
21 |
+
"OPENAI_API_KEY environment variable is not set. Please set it to your OpenAI API key."
|
22 |
+
)
|
23 |
+
openai.api_key = self.openai_api_key
|
24 |
+
self.embeddings_model_name = embeddings_model_name
|
25 |
+
|
26 |
+
async def async_get_embeddings(self, list_of_text: List[str]) -> List[List[float]]:
|
27 |
+
return await aget_embeddings(
|
28 |
+
list_of_text=list_of_text, engine=self.embeddings_model_name
|
29 |
+
)
|
30 |
+
|
31 |
+
async def async_get_embedding(self, text: str) -> List[float]:
|
32 |
+
return await aget_embedding(text=text, engine=self.embeddings_model_name)
|
33 |
+
|
34 |
+
def get_embeddings(self, list_of_text: List[str]) -> List[List[float]]:
|
35 |
+
return get_embeddings(
|
36 |
+
list_of_text=list_of_text, engine=self.embeddings_model_name
|
37 |
+
)
|
38 |
+
|
39 |
+
def get_embedding(self, text: str) -> List[float]:
|
40 |
+
return get_embedding(text=text, engine=self.embeddings_model_name)
|
41 |
+
|
42 |
+
|
43 |
+
if __name__ == "__main__":
|
44 |
+
embedding_model = EmbeddingModel()
|
45 |
+
print(embedding_model.get_embedding("Hello, world!"))
|
46 |
+
print(embedding_model.get_embeddings(["Hello, world!", "Goodbye, world!"]))
|
47 |
+
print(asyncio.run(embedding_model.async_get_embedding("Hello, world!")))
|
48 |
+
print(
|
49 |
+
asyncio.run(
|
50 |
+
embedding_model.async_get_embeddings(["Hello, world!", "Goodbye, world!"])
|
51 |
+
)
|
52 |
+
)
|
aimakerspace/openai_utils/prompts.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
|
4 |
+
class BasePrompt:
|
5 |
+
def __init__(self, prompt):
|
6 |
+
"""
|
7 |
+
Initializes the BasePrompt object with a prompt template.
|
8 |
+
|
9 |
+
:param prompt: A string that can contain placeholders within curly braces
|
10 |
+
"""
|
11 |
+
self.prompt = prompt
|
12 |
+
self._pattern = re.compile(r"\{([^}]+)\}")
|
13 |
+
|
14 |
+
def format_prompt(self, **kwargs):
|
15 |
+
"""
|
16 |
+
Formats the prompt string using the keyword arguments provided.
|
17 |
+
|
18 |
+
:param kwargs: The values to substitute into the prompt string
|
19 |
+
:return: The formatted prompt string
|
20 |
+
"""
|
21 |
+
matches = self._pattern.findall(self.prompt)
|
22 |
+
return self.prompt.format(**{match: kwargs.get(match, "") for match in matches})
|
23 |
+
|
24 |
+
def get_input_variables(self):
|
25 |
+
"""
|
26 |
+
Gets the list of input variable names from the prompt string.
|
27 |
+
|
28 |
+
:return: List of input variable names
|
29 |
+
"""
|
30 |
+
return self._pattern.findall(self.prompt)
|
31 |
+
|
32 |
+
|
33 |
+
class RolePrompt(BasePrompt):
|
34 |
+
def __init__(self, prompt, role: str):
|
35 |
+
"""
|
36 |
+
Initializes the RolePrompt object with a prompt template and a role.
|
37 |
+
|
38 |
+
:param prompt: A string that can contain placeholders within curly braces
|
39 |
+
:param role: The role for the message ('system', 'user', or 'assistant')
|
40 |
+
"""
|
41 |
+
super().__init__(prompt)
|
42 |
+
self.role = role
|
43 |
+
|
44 |
+
def create_message(self, **kwargs):
|
45 |
+
"""
|
46 |
+
Creates a message dictionary with a role and a formatted message.
|
47 |
+
|
48 |
+
:param kwargs: The values to substitute into the prompt string
|
49 |
+
:return: Dictionary containing the role and the formatted message
|
50 |
+
"""
|
51 |
+
return {"role": self.role, "content": self.format_prompt(**kwargs)}
|
52 |
+
|
53 |
+
|
54 |
+
class SystemRolePrompt(RolePrompt):
|
55 |
+
def __init__(self, prompt: str):
|
56 |
+
super().__init__(prompt, "system")
|
57 |
+
|
58 |
+
|
59 |
+
class UserRolePrompt(RolePrompt):
|
60 |
+
def __init__(self, prompt: str):
|
61 |
+
super().__init__(prompt, "user")
|
62 |
+
|
63 |
+
|
64 |
+
class AssistantRolePrompt(RolePrompt):
|
65 |
+
def __init__(self, prompt: str):
|
66 |
+
super().__init__(prompt, "assistant")
|
67 |
+
|
68 |
+
|
69 |
+
if __name__ == "__main__":
|
70 |
+
prompt = BasePrompt("Hello {name}, you are {age} years old")
|
71 |
+
print(prompt.format_prompt(name="John", age=30))
|
72 |
+
|
73 |
+
prompt = SystemRolePrompt("Hello {name}, you are {age} years old")
|
74 |
+
print(prompt.create_message(name="John", age=30))
|
75 |
+
print(prompt.get_input_variables())
|
aimakerspace/text_utils.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import List
|
3 |
+
|
4 |
+
|
5 |
+
class TextFileLoader:
|
6 |
+
def __init__(self, path: str, encoding: str = "utf-8"):
|
7 |
+
self.documents = []
|
8 |
+
self.path = path
|
9 |
+
self.encoding = encoding
|
10 |
+
|
11 |
+
def load(self):
|
12 |
+
if os.path.isdir(self.path):
|
13 |
+
self.load_directory()
|
14 |
+
elif os.path.isfile(self.path) and self.path.endswith(".txt"):
|
15 |
+
self.load_file()
|
16 |
+
else:
|
17 |
+
raise ValueError(
|
18 |
+
"Provided path is neither a valid directory nor a .txt file."
|
19 |
+
)
|
20 |
+
|
21 |
+
def load_file(self):
|
22 |
+
with open(self.path, "r", encoding=self.encoding) as f:
|
23 |
+
self.documents.append(f.read())
|
24 |
+
|
25 |
+
def load_directory(self):
|
26 |
+
for root, _, files in os.walk(self.path):
|
27 |
+
for file in files:
|
28 |
+
if file.endswith(".txt"):
|
29 |
+
with open(
|
30 |
+
os.path.join(root, file), "r", encoding=self.encoding
|
31 |
+
) as f:
|
32 |
+
self.documents.append(f.read())
|
33 |
+
|
34 |
+
def load_documents(self):
|
35 |
+
self.load()
|
36 |
+
return self.documents
|
37 |
+
|
38 |
+
|
39 |
+
class CharacterTextSplitter:
|
40 |
+
def __init__(
|
41 |
+
self,
|
42 |
+
chunk_size: int = 1000,
|
43 |
+
chunk_overlap: int = 200,
|
44 |
+
):
|
45 |
+
assert (
|
46 |
+
chunk_size > chunk_overlap
|
47 |
+
), "Chunk size must be greater than chunk overlap"
|
48 |
+
|
49 |
+
self.chunk_size = chunk_size
|
50 |
+
self.chunk_overlap = chunk_overlap
|
51 |
+
|
52 |
+
def split(self, text: str) -> List[str]:
|
53 |
+
chunks = []
|
54 |
+
for i in range(0, len(text), self.chunk_size - self.chunk_overlap):
|
55 |
+
chunks.append(text[i : i + self.chunk_size])
|
56 |
+
return chunks
|
57 |
+
|
58 |
+
def split_texts(self, texts: List[str]) -> List[str]:
|
59 |
+
chunks = []
|
60 |
+
for text in texts:
|
61 |
+
chunks.extend(self.split(text))
|
62 |
+
return chunks
|
63 |
+
|
64 |
+
|
65 |
+
if __name__ == "__main__":
|
66 |
+
loader = TextFileLoader("data/KingLear.txt")
|
67 |
+
loader.load()
|
68 |
+
splitter = CharacterTextSplitter()
|
69 |
+
chunks = splitter.split_texts(loader.documents)
|
70 |
+
print(len(chunks))
|
71 |
+
print(chunks[0])
|
72 |
+
print("--------")
|
73 |
+
print(chunks[1])
|
74 |
+
print("--------")
|
75 |
+
print(chunks[-2])
|
76 |
+
print("--------")
|
77 |
+
print(chunks[-1])
|
aimakerspace/vectordatabase.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from collections import defaultdict
|
3 |
+
from typing import List, Tuple, Callable
|
4 |
+
from aimakerspace.openai_utils.embedding import EmbeddingModel
|
5 |
+
import asyncio
|
6 |
+
|
7 |
+
|
8 |
+
def cosine_similarity(vector_a: np.array, vector_b: np.array) -> float:
|
9 |
+
"""Computes the cosine similarity between two vectors."""
|
10 |
+
dot_product = np.dot(vector_a, vector_b)
|
11 |
+
norm_a = np.linalg.norm(vector_a)
|
12 |
+
norm_b = np.linalg.norm(vector_b)
|
13 |
+
return dot_product / (norm_a * norm_b)
|
14 |
+
|
15 |
+
|
16 |
+
class VectorDatabase:
|
17 |
+
def __init__(self, embedding_model: EmbeddingModel = None):
|
18 |
+
self.vectors = defaultdict(np.array)
|
19 |
+
self.embedding_model = embedding_model or EmbeddingModel()
|
20 |
+
|
21 |
+
def insert(self, key: str, vector: np.array) -> None:
|
22 |
+
self.vectors[key] = vector
|
23 |
+
|
24 |
+
def search(
|
25 |
+
self,
|
26 |
+
query_vector: np.array,
|
27 |
+
k: int,
|
28 |
+
distance_measure: Callable = cosine_similarity,
|
29 |
+
) -> List[Tuple[str, float]]:
|
30 |
+
scores = [
|
31 |
+
(key, distance_measure(query_vector, vector))
|
32 |
+
for key, vector in self.vectors.items()
|
33 |
+
]
|
34 |
+
return sorted(scores, key=lambda x: x[1], reverse=True)[:k]
|
35 |
+
|
36 |
+
def search_by_text(
|
37 |
+
self,
|
38 |
+
query_text: str,
|
39 |
+
k: int,
|
40 |
+
distance_measure: Callable = cosine_similarity,
|
41 |
+
return_as_text: bool = False,
|
42 |
+
) -> List[Tuple[str, float]]:
|
43 |
+
query_vector = self.embedding_model.get_embedding(query_text)
|
44 |
+
results = self.search(query_vector, k, distance_measure)
|
45 |
+
return [result[0] for result in results] if return_as_text else results
|
46 |
+
|
47 |
+
def retrieve_from_key(self, key: str) -> np.array:
|
48 |
+
return self.vectors.get(key, None)
|
49 |
+
|
50 |
+
async def abuild_from_list(self, list_of_text: List[str]) -> "VectorDatabase":
|
51 |
+
embeddings = await self.embedding_model.async_get_embeddings(list_of_text)
|
52 |
+
for text, embedding in zip(list_of_text, embeddings):
|
53 |
+
self.insert(text, np.array(embedding))
|
54 |
+
return self
|
55 |
+
|
56 |
+
|
57 |
+
if __name__ == "__main__":
|
58 |
+
list_of_text = [
|
59 |
+
"I like to eat broccoli and bananas.",
|
60 |
+
"I ate a banana and spinach smoothie for breakfast.",
|
61 |
+
"Chinchillas and kittens are cute.",
|
62 |
+
"My sister adopted a kitten yesterday.",
|
63 |
+
"Look at this cute hamster munching on a piece of broccoli.",
|
64 |
+
]
|
65 |
+
|
66 |
+
vector_db = VectorDatabase()
|
67 |
+
vector_db = asyncio.run(vector_db.abuild_from_list(list_of_text))
|
68 |
+
k = 2
|
69 |
+
|
70 |
+
searched_vector = vector_db.search_by_text("I think fruit is awesome!", k=k)
|
71 |
+
print(f"Closest {k} vector(s):", searched_vector)
|
72 |
+
|
73 |
+
retrieved_vector = vector_db.retrieve_from_key(
|
74 |
+
"I like to eat broccoli and bananas."
|
75 |
+
)
|
76 |
+
print("Retrieved vector:", retrieved_vector)
|
77 |
+
|
78 |
+
relevant_texts = vector_db.search_by_text(
|
79 |
+
"I think fruit is awesome!", k=k, return_as_text=True
|
80 |
+
)
|
81 |
+
print(f"Closest {k} text(s):", relevant_texts)
|
app.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dotenv import load_dotenv
|
2 |
+
import openai #importing openai for API usage
|
3 |
+
import chainlit as cl #importing chainlit for our app
|
4 |
+
from aimakerspace.vectordatabase import VectorDatabase
|
5 |
+
from aimakerspace.vectordatabase import asyncio
|
6 |
+
from aimakerspace.text_utils import TextFileLoader
|
7 |
+
import os
|
8 |
+
import openai
|
9 |
+
from getpass import getpass
|
10 |
+
from aimakerspace.openai_utils.prompts import (
|
11 |
+
UserRolePrompt,
|
12 |
+
SystemRolePrompt,
|
13 |
+
AssistantRolePrompt,
|
14 |
+
)
|
15 |
+
from aimakerspace.openai_utils.chatmodel import ChatOpenAI
|
16 |
+
from chainlit.prompt import Prompt, PromptMessage # importing prompt tools
|
17 |
+
from chainlit.playground.providers import ChatOpenAI # importing ChatOpenAI tools
|
18 |
+
|
19 |
+
load_dotenv()
|
20 |
+
|
21 |
+
openai.api_key = os.environ["OPENAI_API_KEY"]
|
22 |
+
def load(filename):
|
23 |
+
text_loader = TextFileLoader(filename)
|
24 |
+
documents = text_loader.load_documents()
|
25 |
+
return documents
|
26 |
+
|
27 |
+
model_name = "gpt-4"
|
28 |
+
|
29 |
+
filname = "data/KingLear.txt"
|
30 |
+
openai.api_key = getpass("OpenAI API Key: ")
|
31 |
+
os.environ["OPENAI_API_KEY"] = openai.api_key
|
32 |
+
vector_db = VectorDatabase()
|
33 |
+
split_documents = load(filname)
|
34 |
+
vector_db = asyncio.run(vector_db.abuild_from_list(split_documents))
|
35 |
+
chat_openai = ChatOpenAI()
|
36 |
+
user_prompt_template = "{content}"
|
37 |
+
user_role_prompt = UserRolePrompt(user_prompt_template)
|
38 |
+
system_prompt_template = (
|
39 |
+
"You are an expert in {expertise}, you always answer in a kind way."
|
40 |
+
)
|
41 |
+
system_role_prompt = SystemRolePrompt(system_prompt_template)
|
42 |
+
RAQA_PROMPT_TEMPLATE = """
|
43 |
+
Use the provided context to answer the user's query.
|
44 |
+
|
45 |
+
You may not answer the user's query unless there is specific context in the following text.
|
46 |
+
|
47 |
+
If you do not know the answer, or cannot answer, please respond with "I don't know".
|
48 |
+
|
49 |
+
Context:
|
50 |
+
{context}
|
51 |
+
"""
|
52 |
+
|
53 |
+
raqa_prompt = SystemRolePrompt(RAQA_PROMPT_TEMPLATE)
|
54 |
+
|
55 |
+
USER_PROMPT_TEMPLATE = """
|
56 |
+
User Query:
|
57 |
+
{user_query}
|
58 |
+
"""
|
59 |
+
|
60 |
+
user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)
|
61 |
+
class RetrievalAugmentedQAPipeline:
|
62 |
+
def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:
|
63 |
+
self.llm = llm
|
64 |
+
self.vector_db_retriever = vector_db_retriever
|
65 |
+
|
66 |
+
def run_pipeline(self, user_query: str) -> str:
|
67 |
+
context_list = self.vector_db_retriever.search_by_text(user_query, k=4)
|
68 |
+
|
69 |
+
context_prompt = ""
|
70 |
+
for context in context_list:
|
71 |
+
context_prompt += context[0] + "\n"
|
72 |
+
|
73 |
+
formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)
|
74 |
+
|
75 |
+
formatted_user_prompt = user_prompt.create_message(user_query=user_query)
|
76 |
+
|
77 |
+
return self.llm.run([formatted_system_prompt, formatted_user_prompt])
|
78 |
+
|
79 |
+
|
80 |
+
@cl.on_chat_start # marks a function that will be executed at the start of a user session
|
81 |
+
def start_chat():
|
82 |
+
cl.user_session.set(
|
83 |
+
"message_history",
|
84 |
+
[{"role": "system", "content": "You are a helpful assistant."}],
|
85 |
+
)
|
86 |
+
settings = {
|
87 |
+
"temperature": 0.7, # higher value increases output diveresity/randomness
|
88 |
+
"max_tokens": 500, # maximum length of output response
|
89 |
+
"top_p": 1, # choose only the top x% of possible words to return
|
90 |
+
"frequency_penalty": 0, # higher value will result in the model being more conservative in its use of repeated tokens.
|
91 |
+
"presence_penalty": 0, # higher value will result in the model being more likely to generate tokens that have not yet been included in the generated text
|
92 |
+
}
|
93 |
+
cl.user_session.set("settings", settings)
|
94 |
+
|
95 |
+
|
96 |
+
@cl.on_message # this function will be called every time a user inputs a message in the UI
|
97 |
+
async def main(message: str):
|
98 |
+
|
99 |
+
qaPipeline = RetrievalAugmentedQAPipeline(vector_db_retriever=vector_db, llm=chat_openai)
|
100 |
+
await qaPipeline.run_pipeline(user_query=message)
|
101 |
+
|
102 |
+
|
103 |
+
|
104 |
+
|
105 |
+
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
|
110 |
+
|
111 |
+
|
112 |
+
|
113 |
+
|
114 |
+
|
data/KingLear.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
images/docchain_img.png
ADDED
![]() |
images/raqaapp_img.png
ADDED
![]() |
images/texsplitter_img.png
ADDED
![]() |
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
numpy==1.25.2
|
2 |
+
openai==0.27.8
|
3 |
+
python-dotenv==1.0.0
|
4 |
+
pandas
|
5 |
+
scikit-learn
|
6 |
+
ipykernel
|
7 |
+
matplotlib
|
8 |
+
plotly
|
9 |
+
chainlit==0.7.0
|