Spaces:
Sleeping
Sleeping
Add application file
Browse files- Dockerfile +11 -0
- Python RAQA Example.ipynb +984 -0
- README.md +50 -11
- app.py +95 -0
- raqa.py +91 -0
- requirements.txt +11 -0
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
@@ -0,0 +1,984 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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": 2,
|
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": 3,
|
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": 4,
|
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": 5,
|
101 |
+
"metadata": {},
|
102 |
+
"outputs": [
|
103 |
+
{
|
104 |
+
"data": {
|
105 |
+
"text/plain": [
|
106 |
+
"1"
|
107 |
+
]
|
108 |
+
},
|
109 |
+
"execution_count": 5,
|
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": 6,
|
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": 7,
|
181 |
+
"metadata": {},
|
182 |
+
"outputs": [
|
183 |
+
{
|
184 |
+
"data": {
|
185 |
+
"text/plain": [
|
186 |
+
"189"
|
187 |
+
]
|
188 |
+
},
|
189 |
+
"execution_count": 7,
|
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": 8,
|
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": 8,
|
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": 9,
|
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": 10,
|
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": 11,
|
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.8344666931475854),\n",
|
363 |
+
" (\",\\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",
|
364 |
+
" 0.8218615790372595),\n",
|
365 |
+
" (\" Caius?\\nKING LEAR\\nHe's a good fellow, I can tell you that;\\nHe'll strike, and quickly too: he's dead and rotten.\\nKENT\\nNo, my good lord; I am the very man,--\\nKING LEAR\\nI'll see that straight.\\nKENT\\nThat, from your first of difference and decay,\\nHave follow'd your sad steps.\\nKING LEAR\\nYou are welcome hither.\\nKENT\\nNor no man else: all's cheerless, dark, and deadly.\\nYour eldest daughters have fordone them selves,\\nAnd desperately are dead.\\nKING LEAR\\nAy, so I think.\\nALBANY\\nHe knows not what he says: and vain it is\\nThat we present us to him.\\nEDGAR\\nVery bootless.\\nEnter a Captain\\n\\nCaptain\\nEdmund is dead, my lord.\\nALBANY\\nThat's but a trifle here.\\nYou lords and noble friends, know our intent.\\nWhat comfort to this great decay may come\\nShall be applied: for us we will resign,\\nDuring the life of this old majesty,\\nTo him our absolute power:\\nTo EDGAR and KENT\\n\\nyou, to your rights:\\nWith boot, and such addition as your honours\\nHave more than merited. All friends shall taste\\nThe wages of their virtue, and \",\n",
|
366 |
+
" 0.8210514859927185)]"
|
367 |
+
]
|
368 |
+
},
|
369 |
+
"execution_count": 11,
|
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": 14,
|
556 |
+
"metadata": {},
|
557 |
+
"outputs": [
|
558 |
+
{
|
559 |
+
"ename": "ModuleNotFoundError",
|
560 |
+
"evalue": "No module named 'prompts'",
|
561 |
+
"output_type": "error",
|
562 |
+
"traceback": [
|
563 |
+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
564 |
+
"\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
|
565 |
+
"\u001b[1;32m/home/rlpeter70/LLMO-Cohort-3/Week 1/Thursday - Retrieval Augmented Generation QA Application /Python RAQA Example.ipynb Cell 34\u001b[0m line \u001b[0;36m7\n\u001b[1;32m <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=0'>1</a>\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39maimakerspace\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mopenai_utils\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mprompts\u001b[39;00m \u001b[39mimport\u001b[39;00m (\n\u001b[1;32m <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=1'>2</a>\u001b[0m UserRolePrompt,\n\u001b[1;32m <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=2'>3</a>\u001b[0m SystemRolePrompt,\n\u001b[1;32m <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=3'>4</a>\u001b[0m AssistantRolePrompt,\n\u001b[1;32m <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=4'>5</a>\u001b[0m )\n\u001b[0;32m----> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=6'>7</a>\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39maimakerspace\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mopenai_utils\u001b[39;00m\u001b[39m.\u001b[39;00m\u001b[39mchatmodel\u001b[39;00m \u001b[39mimport\u001b[39;00m ChatOpenAI\n\u001b[1;32m <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a>\u001b[0m chat_openai \u001b[39m=\u001b[39m ChatOpenAI()\n\u001b[1;32m <a href='vscode-notebook-cell://wsl%2Bubuntu/home/rlpeter70/LLMO-Cohort-3/Week%201/Thursday%20-%20Retrieval%20Augmented%20Generation%20QA%20Application%20/Python%20RAQA%20Example.ipynb#X45sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a>\u001b[0m user_prompt_template \u001b[39m=\u001b[39m \u001b[39m\"\u001b[39m\u001b[39m{content}\u001b[39;00m\u001b[39m\"\u001b[39m\n",
|
566 |
+
"File \u001b[0;32m~/LLMO-Cohort-3/Week 1/Thursday - Retrieval Augmented Generation QA Application /aimakerspace/openai_utils/chatmodel.py:3\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mopenai\u001b[39;00m \u001b[39mimport\u001b[39;00m OpenAI\n\u001b[1;32m 2\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mdotenv\u001b[39;00m \u001b[39mimport\u001b[39;00m load_dotenv\n\u001b[0;32m----> 3\u001b[0m \u001b[39mfrom\u001b[39;00m \u001b[39mprompts\u001b[39;00m \u001b[39mimport\u001b[39;00m UserRolePrompt, SystemRolePrompt\n\u001b[1;32m 4\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mos\u001b[39;00m\n\u001b[1;32m 6\u001b[0m load_dotenv()\n",
|
567 |
+
"\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'prompts'"
|
568 |
+
]
|
569 |
+
}
|
570 |
+
],
|
571 |
+
"source": [
|
572 |
+
"from aimakerspace.openai_utils.prompts import (\n",
|
573 |
+
" UserRolePrompt,\n",
|
574 |
+
" SystemRolePrompt,\n",
|
575 |
+
" AssistantRolePrompt,\n",
|
576 |
+
")\n",
|
577 |
+
"\n",
|
578 |
+
"from aimakerspace.openai_utils.chatmodel import ChatOpenAI\n",
|
579 |
+
"\n",
|
580 |
+
"chat_openai = ChatOpenAI()\n",
|
581 |
+
"user_prompt_template = \"{content}\"\n",
|
582 |
+
"user_role_prompt = UserRolePrompt(user_prompt_template)\n",
|
583 |
+
"system_prompt_template = (\n",
|
584 |
+
" \"You are an expert in {expertise}, you always answer in a kind way.\"\n",
|
585 |
+
")\n",
|
586 |
+
"system_role_prompt = SystemRolePrompt(system_prompt_template)\n",
|
587 |
+
"\n",
|
588 |
+
"messages = [\n",
|
589 |
+
" user_role_prompt.create_message(\n",
|
590 |
+
" content=\"What is the best way to write a loop?\"\n",
|
591 |
+
" ),\n",
|
592 |
+
" system_role_prompt.create_message(expertise=\"Python\"),\n",
|
593 |
+
"]\n",
|
594 |
+
"\n",
|
595 |
+
"response = chat_openai.run(messages)"
|
596 |
+
]
|
597 |
+
},
|
598 |
+
{
|
599 |
+
"cell_type": "code",
|
600 |
+
"execution_count": null,
|
601 |
+
"metadata": {},
|
602 |
+
"outputs": [
|
603 |
+
{
|
604 |
+
"name": "stdout",
|
605 |
+
"output_type": "stream",
|
606 |
+
"text": [
|
607 |
+
"The best way to write a loop depends on the specific requirements and context of the problem you are trying to solve. However, here are some general principles that can help you write an effective loop:\n",
|
608 |
+
"\n",
|
609 |
+
"1. Identify the type of loop needed: There are different types of loops, such as `for` loops and `while` loops. Choose the one that suits your situation best.\n",
|
610 |
+
"\n",
|
611 |
+
"2. Set an appropriate loop condition: Make sure the loop condition is set correctly to ensure that the loop runs as intended. If using a `for` loop, ensure the iterable is suitable for the loop.\n",
|
612 |
+
"\n",
|
613 |
+
"3. Initialize variables outside the loop when necessary: If you need to use a variable within the loop, make sure to initialize it outside the loop, so it doesn't get reset with each iteration unless desired.\n",
|
614 |
+
"\n",
|
615 |
+
"4. Use meaningful variable names: Choose variable names that are descriptive and help others (including your future self) understand the purpose of the loop and its associated variables.\n",
|
616 |
+
"\n",
|
617 |
+
"5. Keep the loop body concise and focused: Ensure that the tasks performed within the loop are clear and concise. If your loop body becomes too long or complex, consider moving some functionality into separate functions or methods for better readability and maintainability.\n",
|
618 |
+
"\n",
|
619 |
+
"6. Avoid infinite loops: Make sure your loop has a proper termination condition to prevent it from running indefinitely. Otherwise, your program may hang or crash.\n",
|
620 |
+
"\n",
|
621 |
+
"7. Test and debug: After writing your loop, thoroughly test it with different inputs to ensure it behaves as expected. Use debugging tools if necessary to identify and fix any errors or logical issues.\n",
|
622 |
+
"\n",
|
623 |
+
"Remember, programming is a creative process, and there can be multiple valid approaches to writing a loop. Consider the specific requirements of your problem, and choose the approach that best suits your needs while maintaining readability and maintainability.\n"
|
624 |
+
]
|
625 |
+
}
|
626 |
+
],
|
627 |
+
"source": [
|
628 |
+
"print(response)"
|
629 |
+
]
|
630 |
+
},
|
631 |
+
{
|
632 |
+
"cell_type": "markdown",
|
633 |
+
"metadata": {},
|
634 |
+
"source": [
|
635 |
+
"### Retrieval Augmented Question Answering Prompt\n",
|
636 |
+
"\n",
|
637 |
+
"Now we can create a RAQA prompt - which will help our system behave in a way that makes sense!\n",
|
638 |
+
"\n",
|
639 |
+
"There is much you could do here, many tweaks and improvements to be made!"
|
640 |
+
]
|
641 |
+
},
|
642 |
+
{
|
643 |
+
"cell_type": "code",
|
644 |
+
"execution_count": null,
|
645 |
+
"metadata": {},
|
646 |
+
"outputs": [],
|
647 |
+
"source": [
|
648 |
+
"RAQA_PROMPT_TEMPLATE = \"\"\"\n",
|
649 |
+
"Use the provided context to answer the user's query. \n",
|
650 |
+
"\n",
|
651 |
+
"You may not answer the user's query unless there is specific context in the following text.\n",
|
652 |
+
"\n",
|
653 |
+
"If you do not know the answer, or cannot answer, please respond with \"I don't know\".\n",
|
654 |
+
"\n",
|
655 |
+
"Context:\n",
|
656 |
+
"{context}\n",
|
657 |
+
"\"\"\"\n",
|
658 |
+
"\n",
|
659 |
+
"raqa_prompt = SystemRolePrompt(RAQA_PROMPT_TEMPLATE)\n",
|
660 |
+
"\n",
|
661 |
+
"USER_PROMPT_TEMPLATE = \"\"\"\n",
|
662 |
+
"User Query:\n",
|
663 |
+
"{user_query}\n",
|
664 |
+
"\"\"\"\n",
|
665 |
+
"\n",
|
666 |
+
"user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)\n",
|
667 |
+
"\n",
|
668 |
+
"class RetrievalAugmentedQAPipeline:\n",
|
669 |
+
" def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:\n",
|
670 |
+
" self.llm = llm\n",
|
671 |
+
" self.vector_db_retriever = vector_db_retriever\n",
|
672 |
+
"\n",
|
673 |
+
" def run_pipeline(self, user_query: str) -> str:\n",
|
674 |
+
" context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
|
675 |
+
" \n",
|
676 |
+
" context_prompt = \"\"\n",
|
677 |
+
" for context in context_list:\n",
|
678 |
+
" context_prompt += context[0] + \"\\n\"\n",
|
679 |
+
"\n",
|
680 |
+
" formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)\n",
|
681 |
+
"\n",
|
682 |
+
" formatted_user_prompt = user_prompt.create_message(user_query=user_query)\n",
|
683 |
+
" \n",
|
684 |
+
" return self.llm.run([formatted_system_prompt, formatted_user_prompt])"
|
685 |
+
]
|
686 |
+
},
|
687 |
+
{
|
688 |
+
"cell_type": "code",
|
689 |
+
"execution_count": null,
|
690 |
+
"metadata": {},
|
691 |
+
"outputs": [],
|
692 |
+
"source": [
|
693 |
+
"retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
|
694 |
+
" vector_db_retriever=vector_db,\n",
|
695 |
+
" llm=chat_openai\n",
|
696 |
+
")"
|
697 |
+
]
|
698 |
+
},
|
699 |
+
{
|
700 |
+
"cell_type": "code",
|
701 |
+
"execution_count": null,
|
702 |
+
"metadata": {},
|
703 |
+
"outputs": [
|
704 |
+
{
|
705 |
+
"data": {
|
706 |
+
"text/plain": [
|
707 |
+
"'King Lear is a character in the play \"King Lear\" by William Shakespeare. He is the king of Britain and the protagonist of the play. In the context provided, King Lear is questioning his own identity and is struggling with the actions of his daughters.'"
|
708 |
+
]
|
709 |
+
},
|
710 |
+
"execution_count": 15,
|
711 |
+
"metadata": {},
|
712 |
+
"output_type": "execute_result"
|
713 |
+
}
|
714 |
+
],
|
715 |
+
"source": [
|
716 |
+
"retrieval_augmented_qa_pipeline.run_pipeline(\"Who is King Lear?\")"
|
717 |
+
]
|
718 |
+
},
|
719 |
+
{
|
720 |
+
"cell_type": "markdown",
|
721 |
+
"metadata": {},
|
722 |
+
"source": [
|
723 |
+
"### Visibility Tooling\n",
|
724 |
+
"\n",
|
725 |
+
"This is great, but what if we wanted to add some visibility to our pipeline?\n",
|
726 |
+
"\n",
|
727 |
+
"Let's use Weights and Biases as a visibility tool!\n",
|
728 |
+
"\n",
|
729 |
+
"The first thing we'll need to do is create a Weights and Biases account and get an API key. \n",
|
730 |
+
"\n",
|
731 |
+
"You can follow the process outlined [here](https://docs.wandb.ai/quickstart) to do exactly that!"
|
732 |
+
]
|
733 |
+
},
|
734 |
+
{
|
735 |
+
"cell_type": "markdown",
|
736 |
+
"metadata": {},
|
737 |
+
"source": [
|
738 |
+
"Now we can get the Weights and Biases dependency and add our key to our env. to begin!"
|
739 |
+
]
|
740 |
+
},
|
741 |
+
{
|
742 |
+
"cell_type": "code",
|
743 |
+
"execution_count": null,
|
744 |
+
"metadata": {},
|
745 |
+
"outputs": [],
|
746 |
+
"source": [
|
747 |
+
"!pip install -q -U wandb"
|
748 |
+
]
|
749 |
+
},
|
750 |
+
{
|
751 |
+
"cell_type": "code",
|
752 |
+
"execution_count": null,
|
753 |
+
"metadata": {},
|
754 |
+
"outputs": [],
|
755 |
+
"source": [
|
756 |
+
"wandb_key = getpass(\"Weights and Biases API Key: \")\n",
|
757 |
+
"os.environ[\"WANDB_API_KEY\"] = wandb_key"
|
758 |
+
]
|
759 |
+
},
|
760 |
+
{
|
761 |
+
"cell_type": "code",
|
762 |
+
"execution_count": null,
|
763 |
+
"metadata": {},
|
764 |
+
"outputs": [],
|
765 |
+
"source": [
|
766 |
+
"import wandb\n",
|
767 |
+
"\n",
|
768 |
+
"os.environ[\"WANDB_NOTEBOOK_NAME\"] = \"Python RAQA Example.ipynb\"\n",
|
769 |
+
"wandb.init(project=\"Visibility Example\")"
|
770 |
+
]
|
771 |
+
},
|
772 |
+
{
|
773 |
+
"cell_type": "markdown",
|
774 |
+
"metadata": {},
|
775 |
+
"source": [
|
776 |
+
"Now we can integrate Weights and Biases into our `RetrievalAugmentedQAPipeline`.\n",
|
777 |
+
"\n",
|
778 |
+
"```python\n",
|
779 |
+
"if self.wandb_project:\n",
|
780 |
+
" root_span = Trace(\n",
|
781 |
+
" name=\"root_span\",\n",
|
782 |
+
" kind=\"llm\",\n",
|
783 |
+
" status_code=status,\n",
|
784 |
+
" status_message=status_message,\n",
|
785 |
+
" start_time_ms=start_time,\n",
|
786 |
+
" end_time_ms=end_time,\n",
|
787 |
+
" metadata={\n",
|
788 |
+
" \"token_usage\" : token_usage\n",
|
789 |
+
" },\n",
|
790 |
+
" inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
|
791 |
+
" outputs= {\"response\" : response_text}\n",
|
792 |
+
" )\n",
|
793 |
+
"\n",
|
794 |
+
" root_span.log(name=\"openai_trace\")\n",
|
795 |
+
"```\n",
|
796 |
+
"\n",
|
797 |
+
"The main things to consider here are how to populate the various fields to make sure we're tracking useful information. \n",
|
798 |
+
"\n",
|
799 |
+
"We'll use the `text_only` flag to ensure we can get detailed information about our LLM call!\n",
|
800 |
+
"\n",
|
801 |
+
"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)"
|
802 |
+
]
|
803 |
+
},
|
804 |
+
{
|
805 |
+
"cell_type": "code",
|
806 |
+
"execution_count": null,
|
807 |
+
"metadata": {},
|
808 |
+
"outputs": [],
|
809 |
+
"source": [
|
810 |
+
"import datetime\n",
|
811 |
+
"from wandb.sdk.data_types.trace_tree import Trace\n",
|
812 |
+
"\n",
|
813 |
+
"class RetrievalAugmentedQAPipeline:\n",
|
814 |
+
" def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase, wandb_project = None) -> None:\n",
|
815 |
+
" self.llm = llm\n",
|
816 |
+
" self.vector_db_retriever = vector_db_retriever\n",
|
817 |
+
" self.wandb_project = wandb_project\n",
|
818 |
+
"\n",
|
819 |
+
" def run_pipeline(self, user_query: str) -> str:\n",
|
820 |
+
" context_list = self.vector_db_retriever.search_by_text(user_query, k=4)\n",
|
821 |
+
" \n",
|
822 |
+
" context_prompt = \"\"\n",
|
823 |
+
" for context in context_list:\n",
|
824 |
+
" context_prompt += context[0] + \"\\n\"\n",
|
825 |
+
"\n",
|
826 |
+
" formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)\n",
|
827 |
+
"\n",
|
828 |
+
" formatted_user_prompt = user_prompt.create_message(user_query=user_query)\n",
|
829 |
+
"\n",
|
830 |
+
" \n",
|
831 |
+
" start_time = datetime.datetime.now().timestamp() * 1000\n",
|
832 |
+
"\n",
|
833 |
+
" try:\n",
|
834 |
+
" openai_response = self.llm.run([formatted_system_prompt, formatted_user_prompt], text_only=False)\n",
|
835 |
+
" end_time = datetime.datetime.now().timestamp() * 1000\n",
|
836 |
+
" status = \"success\"\n",
|
837 |
+
" status_message = (None, )\n",
|
838 |
+
" response_text = openai_response.choices[0].message.content\n",
|
839 |
+
" token_usage = dict(openai_response.usage)\n",
|
840 |
+
" model = openai_response.model\n",
|
841 |
+
"\n",
|
842 |
+
" except Exception as e:\n",
|
843 |
+
" end_time = datetime.datetime.now().timestamp() * 1000\n",
|
844 |
+
" status = \"error\"\n",
|
845 |
+
" status_message = str(e)\n",
|
846 |
+
" response_text = \"\"\n",
|
847 |
+
" token_usage = {}\n",
|
848 |
+
" model = \"\"\n",
|
849 |
+
"\n",
|
850 |
+
" if self.wandb_project:\n",
|
851 |
+
" root_span = Trace(\n",
|
852 |
+
" name=\"root_span\",\n",
|
853 |
+
" kind=\"llm\",\n",
|
854 |
+
" status_code=status,\n",
|
855 |
+
" status_message=status_message,\n",
|
856 |
+
" start_time_ms=start_time,\n",
|
857 |
+
" end_time_ms=end_time,\n",
|
858 |
+
" metadata={\n",
|
859 |
+
" \"token_usage\" : token_usage,\n",
|
860 |
+
" \"model_name\" : model\n",
|
861 |
+
" },\n",
|
862 |
+
" inputs= {\"system_prompt\" : formatted_system_prompt, \"user_prompt\" : formatted_user_prompt},\n",
|
863 |
+
" outputs= {\"response\" : response_text}\n",
|
864 |
+
" )\n",
|
865 |
+
"\n",
|
866 |
+
" root_span.log(name=\"openai_trace\")\n",
|
867 |
+
" \n",
|
868 |
+
" return response_text if response_text else \"We ran into an error. Please try again later. Full Error Message: \" + status_message"
|
869 |
+
]
|
870 |
+
},
|
871 |
+
{
|
872 |
+
"cell_type": "code",
|
873 |
+
"execution_count": null,
|
874 |
+
"metadata": {},
|
875 |
+
"outputs": [],
|
876 |
+
"source": [
|
877 |
+
"retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(\n",
|
878 |
+
" vector_db_retriever=vector_db,\n",
|
879 |
+
" llm=chat_openai,\n",
|
880 |
+
" wandb_project=\"LLM Visibility Example\"\n",
|
881 |
+
")"
|
882 |
+
]
|
883 |
+
},
|
884 |
+
{
|
885 |
+
"cell_type": "code",
|
886 |
+
"execution_count": null,
|
887 |
+
"metadata": {},
|
888 |
+
"outputs": [
|
889 |
+
{
|
890 |
+
"data": {
|
891 |
+
"text/plain": [
|
892 |
+
"\"I don't know.\""
|
893 |
+
]
|
894 |
+
},
|
895 |
+
"execution_count": 45,
|
896 |
+
"metadata": {},
|
897 |
+
"output_type": "execute_result"
|
898 |
+
}
|
899 |
+
],
|
900 |
+
"source": [
|
901 |
+
"retrieval_augmented_qa_pipeline.run_pipeline(\"Who is Batman?\")"
|
902 |
+
]
|
903 |
+
},
|
904 |
+
{
|
905 |
+
"cell_type": "code",
|
906 |
+
"execution_count": null,
|
907 |
+
"metadata": {},
|
908 |
+
"outputs": [
|
909 |
+
{
|
910 |
+
"data": {
|
911 |
+
"text/plain": [
|
912 |
+
"\"Cordelia is dead. In the provided context, King Lear enters with Cordelia dead in his arms, expressing his grief and howling for her loss. King Lear realizes that she is gone forever and mourns her death. There is no further information about what specifically caused Cordelia's death.\""
|
913 |
+
]
|
914 |
+
},
|
915 |
+
"execution_count": 46,
|
916 |
+
"metadata": {},
|
917 |
+
"output_type": "execute_result"
|
918 |
+
}
|
919 |
+
],
|
920 |
+
"source": [
|
921 |
+
"retrieval_augmented_qa_pipeline.run_pipeline(\"What happens to Cordelia?\")"
|
922 |
+
]
|
923 |
+
},
|
924 |
+
{
|
925 |
+
"cell_type": "markdown",
|
926 |
+
"metadata": {},
|
927 |
+
"source": [
|
928 |
+
"Navigate to the Weights and Biases \"run\" link to see how your LLM is performing!\n",
|
929 |
+
"\n",
|
930 |
+
"```\n",
|
931 |
+
"View run at YOUR LINK HERE\n",
|
932 |
+
"```"
|
933 |
+
]
|
934 |
+
},
|
935 |
+
{
|
936 |
+
"cell_type": "markdown",
|
937 |
+
"metadata": {},
|
938 |
+
"source": [
|
939 |
+
"# Conclusion\n",
|
940 |
+
"\n",
|
941 |
+
"In this notebook, we've gone through the steps required to create your own simple RAQA application!\n",
|
942 |
+
"\n",
|
943 |
+
"Please feel free to extend this as much as you'd like. "
|
944 |
+
]
|
945 |
+
},
|
946 |
+
{
|
947 |
+
"cell_type": "markdown",
|
948 |
+
"metadata": {},
|
949 |
+
"source": [
|
950 |
+
"# Bonus Challenges\n",
|
951 |
+
"\n",
|
952 |
+
"Challenge 1: \n",
|
953 |
+
"- Implement a new distance measure\n",
|
954 |
+
"- Implement a more efficient vector search\n",
|
955 |
+
"\n",
|
956 |
+
"Challenge 2: \n",
|
957 |
+
"- Create an external VectorStore that can be run/hosted elsewhere\n",
|
958 |
+
"- Build an adapter for that VectorStore here"
|
959 |
+
]
|
960 |
+
}
|
961 |
+
],
|
962 |
+
"metadata": {
|
963 |
+
"kernelspec": {
|
964 |
+
"display_name": "buildyourownlangchain",
|
965 |
+
"language": "python",
|
966 |
+
"name": "python3"
|
967 |
+
},
|
968 |
+
"language_info": {
|
969 |
+
"codemirror_mode": {
|
970 |
+
"name": "ipython",
|
971 |
+
"version": 3
|
972 |
+
},
|
973 |
+
"file_extension": ".py",
|
974 |
+
"mimetype": "text/x-python",
|
975 |
+
"name": "python",
|
976 |
+
"nbconvert_exporter": "python",
|
977 |
+
"pygments_lexer": "ipython3",
|
978 |
+
"version": "3.11.4"
|
979 |
+
},
|
980 |
+
"orig_nbformat": 4
|
981 |
+
},
|
982 |
+
"nbformat": 4,
|
983 |
+
"nbformat_minor": 2
|
984 |
+
}
|
README.md
CHANGED
@@ -1,11 +1,50 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
<p align = "center" draggable=”false” ><img src="https://github.com/AI-Maker-Space/LLM-Dev-101/assets/37101144/d1343317-fa2f-41e1-8af1-1dbb18399719"
|
4 |
+
width="200px"
|
5 |
+
height="auto"/>
|
6 |
+
</p>
|
7 |
+
|
8 |
+
## <h1 align="center" id="heading">🔍Your First Retrieval Augmented Generation QA Application!</h1>
|
9 |
+
|
10 |
+
### Steps to Run:
|
11 |
+
|
12 |
+
1. Create a Python 3.11 environment
|
13 |
+
2. `pip install jupyter` so you can run the notebook
|
14 |
+
|
15 |
+
# Build 🏗️
|
16 |
+
Build a Chainlit App that uses this code.
|
17 |
+
|
18 |
+
# Ship 🚢
|
19 |
+
- Deploy your Chainlit App to Hugging Face
|
20 |
+
- Make a simple diagram of the RAQA process
|
21 |
+
|
22 |
+
# Share 🚀
|
23 |
+
- Show your App in a loom video and explain the diagram
|
24 |
+
- Make a social media post about your final application and tag @AIMakerspace
|
25 |
+
- Share 3 lessons learned
|
26 |
+
- Share 3 lessons not learned
|
27 |
+
|
28 |
+
Here's a template to get your post started!
|
29 |
+
|
30 |
+
```
|
31 |
+
🚀 Exciting News! 🎉
|
32 |
+
|
33 |
+
I just built and shipped my very first Retrieval Augmented Generation QA Application using Chainlit and the OpenAI API! 🤖💼
|
34 |
+
|
35 |
+
🔍 Three Key Takeaways:
|
36 |
+
1️⃣ The power of combining traditional search methods with state-of-the-art generative models is mind-blowing. 🧠✨
|
37 |
+
2️⃣ Collaboration and leveraging community resources like AI Makerspace can greatly accelerate the learning curve. 🌱📈
|
38 |
+
3️⃣ Dive deep, keep iterating, and never stop learning. Each project brings a new set of challenges and equally rewarding lessons. 🔄📚
|
39 |
+
|
40 |
+
A huge shoutout to the @AI Makerspace for their invaluable resources and guidance. 🙌
|
41 |
+
|
42 |
+
Looking forward to more AI-driven adventures! 🌟 Feel free to connect if you'd like to chat more about it! 🤝
|
43 |
+
|
44 |
+
#OpenAI #Chainlit #AIPowered #Innovation #TechJourney
|
45 |
+
```
|
46 |
+
|
47 |
+
|
48 |
+
|
49 |
+
|
50 |
+
|
app.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
!pip install -q -U numpy matplotlib plotly pandas scipy scikit-learn openai python-dotenv
|
2 |
+
|
3 |
+
from aimakerspace.text_utils import TextFileLoader, CharacterTextSplitter
|
4 |
+
from aimakerspace.vectordatabase import VectorDatabase
|
5 |
+
import asyncio
|
6 |
+
|
7 |
+
text_loader = TextFileLoader("data/KingLear.txt")
|
8 |
+
documents = text_loader.load_documents()
|
9 |
+
len(documents)
|
10 |
+
|
11 |
+
text_splitter = CharacterTextSplitter()
|
12 |
+
split_documents = text_splitter.split_texts(documents)
|
13 |
+
|
14 |
+
import os
|
15 |
+
import openai
|
16 |
+
from getpass import getpass
|
17 |
+
|
18 |
+
openai.api_key = getpass("OpenAI API Key: ")
|
19 |
+
os.environ["OPENAI_API_KEY"] = openai.api_key
|
20 |
+
|
21 |
+
vector_db = VectorDatabase()
|
22 |
+
vector_db = asyncio.run(vector_db.abuild_from_list(split_documents))
|
23 |
+
|
24 |
+
import sys
|
25 |
+
sys.path.append('/home/rlpeter70/LLMO-Cohort-3/Week 1/Thursday - Retrieval Augmented Generation QA Application /aimakerspace/openai_utils')
|
26 |
+
|
27 |
+
from aimakerspace.openai_utils.prompts import (
|
28 |
+
UserRolePrompt,
|
29 |
+
SystemRolePrompt,
|
30 |
+
AssistantRolePrompt,
|
31 |
+
)
|
32 |
+
|
33 |
+
from aimakerspace.openai_utils.chatmodel import ChatOpenAI
|
34 |
+
|
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 |
+
|
43 |
+
messages = [
|
44 |
+
user_role_prompt.create_message(
|
45 |
+
content="What is the best way to write a loop?"
|
46 |
+
),
|
47 |
+
system_role_prompt.create_message(expertise="Python"),
|
48 |
+
]
|
49 |
+
|
50 |
+
response = chat_openai.run(messages)
|
51 |
+
|
52 |
+
RAQA_PROMPT_TEMPLATE = """
|
53 |
+
Use the provided context to answer the user's query.
|
54 |
+
|
55 |
+
You may not answer the user's query unless there is specific context in the following text.
|
56 |
+
|
57 |
+
If you do not know the answer, or cannot answer, please respond with "I don't know".
|
58 |
+
|
59 |
+
Context:
|
60 |
+
{context}
|
61 |
+
"""
|
62 |
+
|
63 |
+
raqa_prompt = SystemRolePrompt(RAQA_PROMPT_TEMPLATE)
|
64 |
+
|
65 |
+
USER_PROMPT_TEMPLATE = """
|
66 |
+
User Query:
|
67 |
+
{user_query}
|
68 |
+
"""
|
69 |
+
|
70 |
+
user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)
|
71 |
+
|
72 |
+
class RetrievalAugmentedQAPipeline:
|
73 |
+
def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:
|
74 |
+
self.llm = llm
|
75 |
+
self.vector_db_retriever = vector_db_retriever
|
76 |
+
|
77 |
+
def run_pipeline(self, user_query: str) -> str:
|
78 |
+
context_list = self.vector_db_retriever.search_by_text(user_query, k=4)
|
79 |
+
|
80 |
+
context_prompt = ""
|
81 |
+
for context in context_list:
|
82 |
+
context_prompt += context[0] + "\n"
|
83 |
+
|
84 |
+
formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)
|
85 |
+
|
86 |
+
formatted_user_prompt = user_prompt.create_message(user_query=user_query)
|
87 |
+
|
88 |
+
return self.llm.run([formatted_system_prompt, formatted_user_prompt])
|
89 |
+
|
90 |
+
|
91 |
+
|
92 |
+
retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(
|
93 |
+
vector_db_retriever=vector_db,
|
94 |
+
llm=chat_openai
|
95 |
+
)
|
raqa.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from aimakerspace.text_utils import TextFileLoader, CharacterTextSplitter
|
3 |
+
from aimakerspace.vectordatabase import VectorDatabase
|
4 |
+
import asyncio
|
5 |
+
|
6 |
+
text_loader = TextFileLoader("data/KingLear.txt")
|
7 |
+
documents = text_loader.load_documents()
|
8 |
+
|
9 |
+
text_splitter = CharacterTextSplitter()
|
10 |
+
split_documents = text_splitter.split_texts(documents)
|
11 |
+
|
12 |
+
import os
|
13 |
+
import openai
|
14 |
+
#from getpass import getpass
|
15 |
+
|
16 |
+
#openai.api_key = getpass("OpenAI API Key: ")
|
17 |
+
#os.environ["OPENAI_API_KEY"] = openai.api_key
|
18 |
+
|
19 |
+
vector_db = VectorDatabase()
|
20 |
+
vector_db = asyncio.run(vector_db.abuild_from_list(split_documents))
|
21 |
+
|
22 |
+
|
23 |
+
from aimakerspace.openai_utils.prompts import (
|
24 |
+
UserRolePrompt,
|
25 |
+
SystemRolePrompt,
|
26 |
+
AssistantRolePrompt,
|
27 |
+
)
|
28 |
+
|
29 |
+
from aimakerspace.openai_utils.chatmodel import ChatOpenAI
|
30 |
+
|
31 |
+
chat_openai = ChatOpenAI()
|
32 |
+
user_prompt_template = "{content}"
|
33 |
+
user_role_prompt = UserRolePrompt(user_prompt_template)
|
34 |
+
system_prompt_template = (
|
35 |
+
"You are an expert in {expertise}, you always answer in a kind way."
|
36 |
+
)
|
37 |
+
system_role_prompt = SystemRolePrompt(system_prompt_template)
|
38 |
+
|
39 |
+
messages = [
|
40 |
+
user_role_prompt.create_message(
|
41 |
+
content="What is the best way to write a loop?"
|
42 |
+
),
|
43 |
+
system_role_prompt.create_message(expertise="Python"),
|
44 |
+
]
|
45 |
+
|
46 |
+
response = chat_openai.run(messages)
|
47 |
+
|
48 |
+
RAQA_PROMPT_TEMPLATE = """
|
49 |
+
Use the provided context to answer the user's query.
|
50 |
+
|
51 |
+
You may not answer the user's query unless there is specific context in the following text.
|
52 |
+
|
53 |
+
If you do not know the answer, or cannot answer, please respond with "I don't know".
|
54 |
+
|
55 |
+
Context:
|
56 |
+
{context}
|
57 |
+
"""
|
58 |
+
|
59 |
+
raqa_prompt = SystemRolePrompt(RAQA_PROMPT_TEMPLATE)
|
60 |
+
|
61 |
+
USER_PROMPT_TEMPLATE = """
|
62 |
+
User Query:
|
63 |
+
{user_query}
|
64 |
+
"""
|
65 |
+
|
66 |
+
user_prompt = UserRolePrompt(USER_PROMPT_TEMPLATE)
|
67 |
+
|
68 |
+
class RetrievalAugmentedQAPipeline:
|
69 |
+
def __init__(self, llm: ChatOpenAI(), vector_db_retriever: VectorDatabase) -> None:
|
70 |
+
self.llm = llm
|
71 |
+
self.vector_db_retriever = vector_db_retriever
|
72 |
+
|
73 |
+
def run_pipeline(self, user_query: str) -> str:
|
74 |
+
context_list = self.vector_db_retriever.search_by_text(user_query, k=4)
|
75 |
+
|
76 |
+
context_prompt = ""
|
77 |
+
for context in context_list:
|
78 |
+
context_prompt += context[0] + "\n"
|
79 |
+
|
80 |
+
formatted_system_prompt = raqa_prompt.create_message(context=context_prompt)
|
81 |
+
|
82 |
+
formatted_user_prompt = user_prompt.create_message(user_query=user_query)
|
83 |
+
|
84 |
+
return self.llm.run([formatted_system_prompt, formatted_user_prompt])
|
85 |
+
|
86 |
+
|
87 |
+
|
88 |
+
retrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(
|
89 |
+
vector_db_retriever=vector_db,
|
90 |
+
llm=chat_openai
|
91 |
+
)
|
requirements.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
numpy==1.25.2
|
2 |
+
openai
|
3 |
+
python-dotenv==1.0.0
|
4 |
+
pandas
|
5 |
+
scikit-learn
|
6 |
+
ipykernel
|
7 |
+
matplotlib
|
8 |
+
plotly
|
9 |
+
numpy
|
10 |
+
scipy
|
11 |
+
scikit-learn
|