Omar Solano
commited on
Commit
·
84f8c13
1
Parent(s):
2b85cb1
update embedding model
Browse files- scripts/ai-tutor.ipynb +115 -187
- scripts/gradio-ui.py +10 -4
scripts/ai-tutor.ipynb
CHANGED
@@ -9,19 +9,19 @@
|
|
9 |
},
|
10 |
{
|
11 |
"cell_type": "code",
|
12 |
-
"execution_count":
|
13 |
"metadata": {},
|
14 |
"outputs": [],
|
15 |
"source": [
|
16 |
"import os\n",
|
17 |
"\n",
|
18 |
"# Set the \"OPENAI_API_KEY\" in the Python environment. Will be used by OpenAI client later.\n",
|
19 |
-
"os.environ[\"OPENAI_API_KEY\"] = \"sk
|
20 |
]
|
21 |
},
|
22 |
{
|
23 |
"cell_type": "code",
|
24 |
-
"execution_count":
|
25 |
"metadata": {},
|
26 |
"outputs": [],
|
27 |
"source": [
|
@@ -32,18 +32,7 @@
|
|
32 |
},
|
33 |
{
|
34 |
"cell_type": "code",
|
35 |
-
"execution_count":
|
36 |
-
"metadata": {},
|
37 |
-
"outputs": [],
|
38 |
-
"source": [
|
39 |
-
"from llama_index.llms.openai import OpenAI\n",
|
40 |
-
"\n",
|
41 |
-
"llm = OpenAI(temperature=0.9, model=\"gpt-3.5-turbo\", max_tokens=512)"
|
42 |
-
]
|
43 |
-
},
|
44 |
-
{
|
45 |
-
"cell_type": "code",
|
46 |
-
"execution_count": 4,
|
47 |
"metadata": {},
|
48 |
"outputs": [],
|
49 |
"source": [
|
@@ -57,7 +46,7 @@
|
|
57 |
},
|
58 |
{
|
59 |
"cell_type": "code",
|
60 |
-
"execution_count":
|
61 |
"metadata": {},
|
62 |
"outputs": [],
|
63 |
"source": [
|
@@ -66,219 +55,121 @@
|
|
66 |
"\n",
|
67 |
"# Define a storage context object using the created vector database.\n",
|
68 |
"vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
|
69 |
-
"storage_context = StorageContext.from_defaults(vector_store=vector_store)
|
70 |
-
"\n"
|
71 |
]
|
72 |
},
|
73 |
{
|
74 |
"cell_type": "code",
|
75 |
-
"execution_count":
|
76 |
"metadata": {},
|
77 |
"outputs": [],
|
78 |
"source": [
|
79 |
-
"import
|
80 |
-
"import csv\n",
|
81 |
"from llama_index.core.schema import TextNode\n",
|
82 |
"\n",
|
83 |
-
"def load_csv_files_from_directory(directory):\n",
|
84 |
-
" nodes = []\n",
|
85 |
-
" node_count = 0\n",
|
86 |
-
"\n",
|
87 |
-
" # Iterate over all files in the given directory\n",
|
88 |
-
" for filename in os.listdir(directory):\n",
|
89 |
-
" if filename.endswith(\".csv\"):\n",
|
90 |
-
" filepath = os.path.join(directory, filename)\n",
|
91 |
-
" with open(filepath, mode='r', encoding='utf-8') as file:\n",
|
92 |
-
" csv_reader = csv.reader(file)\n",
|
93 |
-
" headers = next(csv_reader, None) # Read the header row\n",
|
94 |
-
" \n",
|
95 |
-
" # Dynamically determine the column indices\n",
|
96 |
-
" title_idx = headers.index('title') if 'title' in headers else None\n",
|
97 |
-
" url_idx = headers.index('url') if 'url' in headers else None\n",
|
98 |
-
" content_idx = headers.index('content') if 'content' in headers else None\n",
|
99 |
-
" source_idx = headers.index('source') if 'source' in headers else None\n",
|
100 |
-
" \n",
|
101 |
-
" for row in csv_reader:\n",
|
102 |
-
" if title_idx is not None and url_idx is not None and content_idx is not None and source_idx is not None:\n",
|
103 |
-
" node_id = f\"node_{node_count}\"\n",
|
104 |
-
" node = TextNode(\n",
|
105 |
-
" text=row[content_idx],\n",
|
106 |
-
" metadata={\n",
|
107 |
-
" \"title\": row[title_idx],\n",
|
108 |
-
" \"url\": row[url_idx],\n",
|
109 |
-
" \"source\": row[source_idx]\n",
|
110 |
-
" },\n",
|
111 |
-
" id_=node_id\n",
|
112 |
-
" )\n",
|
113 |
-
" nodes.append(node)\n",
|
114 |
-
" node_count += 1\n",
|
115 |
"\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
" return nodes"
|
117 |
]
|
118 |
},
|
119 |
{
|
120 |
"cell_type": "code",
|
121 |
-
"execution_count":
|
122 |
"metadata": {},
|
123 |
-
"outputs": [
|
124 |
-
{
|
125 |
-
"name": "stdout",
|
126 |
-
"output_type": "stream",
|
127 |
-
"text": [
|
128 |
-
"ID: node_0 \n",
|
129 |
-
"Text: # Introduction\n",
|
130 |
-
"This lesson will explore the powerful concept of LangChain memory, which is designed to help chatbots maintain context and improve their conversational capabilities in more details. The traditional approach to chatbot development involves processing user prompts independently and without considering the history of interactions. This can lead to disjointed and unsatisfactory user experiences. LangChain provides memory components to manage and manipulate previous chat messages and incorporate them into chains. This is crucial for chatbots, which require remembering the prior interactions. ![ Image by Midjourney](Mastering%20Memory%20Types%20in%20LangChain%20A%20Comprehensiv%209a0515e0407345888439a8c036e47e43/membot.png) Image by Midjourney By default, LLMs are stateless, which means they process each incoming query in isolation, without considering previous interactions. To overcome this limitation, LangChain offers a standard interface for memory, a variety of memory implementations, and examples of chains and agents that employ memory. It also provides Agents that have access to a suite of Tools. Depending on the user’s input, an Agent can decide which Tools to use., \n",
|
131 |
-
"Metadata: {'title': 'Mastering Memory Types in LangChain: A Comprehensive Guide with Practical Examples', 'url': 'https://learn.activeloop.ai/courses/take/langchain/multimedia/46318209-mastering-memory-types-in-langchain-a-comprehensive-guide-with-practical-examples', 'source': 'langchain_course'}\n",
|
132 |
-
"ID: node_20677 \n",
|
133 |
-
"Text: rue (to lift the ambiguity with a batch of sequences). add_special_tokens (bool, optional, defaults to True) —\n",
|
134 |
-
"Whether or not to add special tokens when encoding the sequences. This will use the underlying\n",
|
135 |
-
"PretrainedTokenizerBase.build_inputs_with_special_tokens function, which defines which tokens are\n",
|
136 |
-
"automatically added to the input ids. This is usefull if you want to add bos or eos tokens\n",
|
137 |
-
"automatically. padding (bool, str or PaddingStrategy, optional, defaults to False) —\n",
|
138 |
-
"Activates and controls padding. Accepts the following values:\n",
|
139 |
-
"True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single\n",
|
140 |
-
"sequence if provided).\n",
|
141 |
-
"'max_length': Pad to a maximum length specified with the argument max_length or to the maximum\n",
|
142 |
-
"acceptable input length for the model if that argument is not provided.\n",
|
143 |
-
"False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different\n",
|
144 |
-
"lengths).\n",
|
145 |
-
" truncation (bool, str or Truncation, \n",
|
146 |
-
"Metadata: {'title': 'PreTrainedTokenizerFast', 'url': 'https://huggingface.co/docs/transformers/main/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast', 'source': 'hf_transformers'}\n"
|
147 |
-
]
|
148 |
-
}
|
149 |
-
],
|
150 |
"source": [
|
151 |
-
"
|
152 |
-
"nodes =
|
|
|
|
|
153 |
"\n",
|
154 |
"node = nodes[0]\n",
|
155 |
"print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")\n",
|
156 |
"\n",
|
157 |
-
"
|
|
|
|
|
158 |
"print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")"
|
159 |
]
|
160 |
},
|
161 |
{
|
162 |
"cell_type": "code",
|
163 |
-
"execution_count":
|
164 |
"metadata": {},
|
165 |
-
"outputs": [
|
166 |
-
{
|
167 |
-
"name": "stderr",
|
168 |
-
"output_type": "stream",
|
169 |
-
"text": [
|
170 |
-
"/Users/omar/Documents/ai_repos/ai-tutor-rag-system/env/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
|
171 |
-
" from .autonotebook import tqdm as notebook_tqdm\n",
|
172 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 5.27it/s]\n",
|
173 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 7.23it/s]\n",
|
174 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:00<00:00, 10.93it/s]\n",
|
175 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 6.51it/s]\n",
|
176 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:00<00:00, 10.74it/s]\n",
|
177 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 9.41it/s]\n",
|
178 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 8.36it/s]\n",
|
179 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 6.57it/s]\n",
|
180 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 7.08it/s]\n",
|
181 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 9.90it/s]\n",
|
182 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 8.22it/s]\n",
|
183 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 6.77it/s]\n",
|
184 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 6.02it/s]\n",
|
185 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 8.81it/s]\n",
|
186 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 7.00it/s]\n",
|
187 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 9.67it/s]\n",
|
188 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 7.71it/s]\n",
|
189 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 9.51it/s]\n",
|
190 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:00<00:00, 10.10it/s]\n",
|
191 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 7.14it/s]\n",
|
192 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 7.08it/s]\n",
|
193 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 7.79it/s]\n",
|
194 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 9.30it/s]\n",
|
195 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:02<00:00, 4.43it/s]\n",
|
196 |
-
"Generating embeddings: 100%|██████████| 10/10 [00:01<00:00, 5.92it/s]\n",
|
197 |
-
"Generating embeddings: 100%|██████████| 7/7 [00:00<00:00, 8.70it/s]\n"
|
198 |
-
]
|
199 |
-
}
|
200 |
-
],
|
201 |
"source": [
|
202 |
"from llama_index.embeddings.openai import OpenAIEmbedding\n",
|
203 |
"from llama_index.core import VectorStoreIndex\n",
|
204 |
"\n",
|
|
|
|
|
|
|
|
|
|
|
205 |
"# Build index / generate embeddings using OpenAI.\n",
|
206 |
-
"index = VectorStoreIndex(nodes=nodes, show_progress=True, use_async=True, storage_context=storage_context, embed_model=
|
207 |
]
|
208 |
},
|
209 |
{
|
210 |
"cell_type": "code",
|
211 |
-
"execution_count":
|
212 |
"metadata": {},
|
213 |
"outputs": [],
|
214 |
"source": [
|
215 |
-
"
|
|
|
|
|
|
|
216 |
]
|
217 |
},
|
218 |
{
|
219 |
"cell_type": "code",
|
220 |
-
"execution_count":
|
221 |
"metadata": {},
|
222 |
"outputs": [],
|
223 |
"source": [
|
224 |
-
"res = query_engine.query(\"
|
225 |
]
|
226 |
},
|
227 |
{
|
228 |
"cell_type": "code",
|
229 |
-
"execution_count":
|
230 |
"metadata": {},
|
231 |
-
"outputs": [
|
232 |
-
{
|
233 |
-
"data": {
|
234 |
-
"text/plain": [
|
235 |
-
"'I cannot provide an answer to the query as there is no relevant information or context provided about \"llama2 llm\" in the given text.'"
|
236 |
-
]
|
237 |
-
},
|
238 |
-
"execution_count": 32,
|
239 |
-
"metadata": {},
|
240 |
-
"output_type": "execute_result"
|
241 |
-
}
|
242 |
-
],
|
243 |
"source": [
|
244 |
"res.response"
|
245 |
]
|
246 |
},
|
247 |
{
|
248 |
"cell_type": "code",
|
249 |
-
"execution_count":
|
250 |
"metadata": {},
|
251 |
-
"outputs": [
|
252 |
-
{
|
253 |
-
"name": "stdout",
|
254 |
-
"output_type": "stream",
|
255 |
-
"text": [
|
256 |
-
"Node ID\t node_1708\n",
|
257 |
-
"Title\t The Generative AI Revolution: Exploring the Current Landscape\n",
|
258 |
-
"Text\t 1. OpenAI's GPT Models Notable Models Task specific models Find model information here: https://platform.openai.com/docs/models/gpt-3 Image & Audio Models OpenAI, the company behind the GPT models, is an AI research and deployment company. The San Francisco-based lab was founded in 2015 as a nonprofit with the goal of building \"artificial general intelligence\" (AGI), which is essentially software as smart as humans. OpenAI conducts innovative research in various fields of AI, such as deep learning, natural language processing, computer vision, and robotics, and develops AI technologies and products intended to solve real-world problems. OpenAI transitioned into a for-profit company in 2019. The company plans to cap the profit of the investors at a fixed multiple of their investment (noted by Sam Altman as currently ranging between 7x and 100x depending on the investment round date and risk). As per the WSJ OpenAI was initially funded by $130m of charity funding (Elon Musk tweeted he contributed $100m) and has since raised at least $13bn led by Microsoft (where OpenAI makes use of Azure cloud credits). With the Microsoft partnership, OpenAI's ChatGPT, along with Microsoft's own search AI, created an improved version of Bing and transformed Microsoft's Office productivity apps. In 2019, OpenAI released GPT-2, a model that could generate realistic human-like text in entire paragraphs with internal consistency, unlike any of the previous models. The next generation, GPT-3, launched in 2020, was trained with 175 billion parameters. GPT-3 is a multi-purpose language tool that users can access without requiring them to learn a programming language or other computer tools. In November 2022, OpenAI released ChatGPT, which is a superior version of the company's earlier text generation models with the capability to generate humanlike prose. After the success of ChatGPT (GPT 3.5), Open AI released GPT-4 in March 2023, which has multimodal capabilities. The model processes both image and text inputs for text generation. The model has a maximum token count of 32,768 capable of generating around 25,000 words as compared to GPT-3.5 which has 4,096 tokens context size. GPT-4 produces 40% more factual responses and its response rate for disallowed content is down by 82% as compared to previous models. (reported by OpenAI) \n",
|
259 |
-
"Score\t 0.7294525989858827\n",
|
260 |
-
"-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
|
261 |
-
"Node ID\t node_19679\n",
|
262 |
-
"Title\t TFBartForConditionalGeneration\n",
|
263 |
-
"Text\t ach tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).\n",
|
264 |
-
"Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be\n",
|
265 |
-
"used (see past_key_values input) to speed up sequential decoding.\n",
|
266 |
-
"decoder_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape\n",
|
267 |
-
"(batch_size, sequence_length, hidden_size).\n",
|
268 |
-
"Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.\n",
|
269 |
-
"decoder_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).\n",
|
270 |
-
"Attentions weights of the decoder, after the attention softmax, used to com\n",
|
271 |
-
"Score\t 0.7243357660195968\n",
|
272 |
-
"-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n"
|
273 |
-
]
|
274 |
-
}
|
275 |
-
],
|
276 |
"source": [
|
277 |
"for src in res.source_nodes:\n",
|
278 |
" print(\"Node ID\\t\", src.node_id)\n",
|
279 |
" print(\"Title\\t\", src.metadata['title'])\n",
|
280 |
" print(\"Text\\t\", src.text)\n",
|
281 |
" print(\"Score\\t\", src.score)\n",
|
|
|
282 |
" print(\"-_\"*20)"
|
283 |
]
|
284 |
},
|
@@ -291,21 +182,21 @@
|
|
291 |
},
|
292 |
{
|
293 |
"cell_type": "code",
|
294 |
-
"execution_count":
|
295 |
"metadata": {},
|
296 |
"outputs": [],
|
297 |
"source": [
|
298 |
"import chromadb\n",
|
299 |
"from llama_index.vector_stores.chroma import ChromaVectorStore\n",
|
300 |
"# Create your index\n",
|
301 |
-
"db2 = chromadb.PersistentClient(path=\"ai-tutor-db\")\n",
|
302 |
"chroma_collection = db2.get_or_create_collection(\"ai-tutor-db\")\n",
|
303 |
"vector_store = ChromaVectorStore(chroma_collection=chroma_collection)"
|
304 |
]
|
305 |
},
|
306 |
{
|
307 |
"cell_type": "code",
|
308 |
-
"execution_count":
|
309 |
"metadata": {},
|
310 |
"outputs": [],
|
311 |
"source": [
|
@@ -316,34 +207,39 @@
|
|
316 |
},
|
317 |
{
|
318 |
"cell_type": "code",
|
319 |
-
"execution_count":
|
320 |
"metadata": {},
|
321 |
"outputs": [],
|
322 |
"source": [
|
323 |
-
"
|
|
|
|
|
|
|
|
|
|
|
324 |
]
|
325 |
},
|
326 |
{
|
327 |
"cell_type": "code",
|
328 |
-
"execution_count":
|
329 |
"metadata": {},
|
330 |
"outputs": [],
|
331 |
"source": [
|
332 |
-
"res = query_engine.query(\"
|
333 |
]
|
334 |
},
|
335 |
{
|
336 |
"cell_type": "code",
|
337 |
-
"execution_count":
|
338 |
"metadata": {},
|
339 |
"outputs": [
|
340 |
{
|
341 |
"data": {
|
342 |
"text/plain": [
|
343 |
-
"'The
|
344 |
]
|
345 |
},
|
346 |
-
"execution_count":
|
347 |
"metadata": {},
|
348 |
"output_type": "execute_result"
|
349 |
}
|
@@ -354,26 +250,58 @@
|
|
354 |
},
|
355 |
{
|
356 |
"cell_type": "code",
|
357 |
-
"execution_count":
|
358 |
"metadata": {},
|
359 |
"outputs": [
|
360 |
{
|
361 |
"name": "stdout",
|
362 |
"output_type": "stream",
|
363 |
"text": [
|
364 |
-
"Node ID\t
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
365 |
"Source\t towards_ai\n",
|
366 |
-
"Title\t
|
367 |
-
"Text\t
|
368 |
-
"Score\t 0.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
369 |
"-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
|
370 |
-
"Node ID\t
|
371 |
"Source\t hf_transformers\n",
|
372 |
-
"Title\t
|
373 |
-
"Text\t
|
374 |
-
"
|
375 |
-
"
|
376 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
377 |
"-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n"
|
378 |
]
|
379 |
}
|
@@ -419,7 +347,7 @@
|
|
419 |
"name": "python",
|
420 |
"nbconvert_exporter": "python",
|
421 |
"pygments_lexer": "ipython3",
|
422 |
-
"version": "3.11.
|
423 |
}
|
424 |
},
|
425 |
"nbformat": 4,
|
|
|
9 |
},
|
10 |
{
|
11 |
"cell_type": "code",
|
12 |
+
"execution_count": null,
|
13 |
"metadata": {},
|
14 |
"outputs": [],
|
15 |
"source": [
|
16 |
"import os\n",
|
17 |
"\n",
|
18 |
"# Set the \"OPENAI_API_KEY\" in the Python environment. Will be used by OpenAI client later.\n",
|
19 |
+
"os.environ[\"OPENAI_API_KEY\"] = \"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\""
|
20 |
]
|
21 |
},
|
22 |
{
|
23 |
"cell_type": "code",
|
24 |
+
"execution_count": null,
|
25 |
"metadata": {},
|
26 |
"outputs": [],
|
27 |
"source": [
|
|
|
32 |
},
|
33 |
{
|
34 |
"cell_type": "code",
|
35 |
+
"execution_count": null,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
"metadata": {},
|
37 |
"outputs": [],
|
38 |
"source": [
|
|
|
46 |
},
|
47 |
{
|
48 |
"cell_type": "code",
|
49 |
+
"execution_count": null,
|
50 |
"metadata": {},
|
51 |
"outputs": [],
|
52 |
"source": [
|
|
|
55 |
"\n",
|
56 |
"# Define a storage context object using the created vector database.\n",
|
57 |
"vector_store = ChromaVectorStore(chroma_collection=chroma_collection)\n",
|
58 |
+
"storage_context = StorageContext.from_defaults(vector_store=vector_store)"
|
|
|
59 |
]
|
60 |
},
|
61 |
{
|
62 |
"cell_type": "code",
|
63 |
+
"execution_count": null,
|
64 |
"metadata": {},
|
65 |
"outputs": [],
|
66 |
"source": [
|
67 |
+
"import json\n",
|
|
|
68 |
"from llama_index.core.schema import TextNode\n",
|
69 |
"\n",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
"\n",
|
71 |
+
"def load_jsonl_create_nodes(filepath):\n",
|
72 |
+
" nodes = [] # List to hold the created node objects\n",
|
73 |
+
" with open(filepath, \"r\") as file:\n",
|
74 |
+
" for line in file:\n",
|
75 |
+
" # Load each line as a JSON object\n",
|
76 |
+
" json_obj = json.loads(line)\n",
|
77 |
+
" # Extract required information\n",
|
78 |
+
" title = json_obj.get(\"title\")\n",
|
79 |
+
" url = json_obj.get(\"url\")\n",
|
80 |
+
" content = json_obj.get(\"content\")\n",
|
81 |
+
" source = json_obj.get(\"source\")\n",
|
82 |
+
" # Create a TextNode object and append to the list\n",
|
83 |
+
" node = TextNode(\n",
|
84 |
+
" text=content,\n",
|
85 |
+
" metadata={\"title\": title, \"url\": url, \"source\": source},\n",
|
86 |
+
" excluded_embed_metadata_keys=[\"title\", \"url\", \"source\"],\n",
|
87 |
+
" excluded_llm_metadata_keys=[\"title\", \"url\", \"source\"],\n",
|
88 |
+
" )\n",
|
89 |
+
" nodes.append(node)\n",
|
90 |
" return nodes"
|
91 |
]
|
92 |
},
|
93 |
{
|
94 |
"cell_type": "code",
|
95 |
+
"execution_count": null,
|
96 |
"metadata": {},
|
97 |
+
"outputs": [],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
"source": [
|
99 |
+
"filepath = \"../data/ai-tutor-csv-files/combined_data_lines.jsonl\"\n",
|
100 |
+
"nodes = load_jsonl_create_nodes(filepath)\n",
|
101 |
+
"\n",
|
102 |
+
"print(f\"Loaded {len(nodes)} nodes/chunks from the JSONL file\\n \")\n",
|
103 |
"\n",
|
104 |
"node = nodes[0]\n",
|
105 |
"print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")\n",
|
106 |
"\n",
|
107 |
+
"print(\"\\n\")\n",
|
108 |
+
"\n",
|
109 |
+
"node = nodes[-10000]\n",
|
110 |
"print(f\"ID: {node.id_} \\nText: {node.text}, \\nMetadata: {node.metadata}\")"
|
111 |
]
|
112 |
},
|
113 |
{
|
114 |
"cell_type": "code",
|
115 |
+
"execution_count": null,
|
116 |
"metadata": {},
|
117 |
+
"outputs": [],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
"source": [
|
119 |
"from llama_index.embeddings.openai import OpenAIEmbedding\n",
|
120 |
"from llama_index.core import VectorStoreIndex\n",
|
121 |
"\n",
|
122 |
+
"# embeds = OpenAIEmbedding(model=\"text-embedding-3-small\", mode=\"similarity\")\n",
|
123 |
+
"# embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"similarity\")\n",
|
124 |
+
"embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"text_search\")\n",
|
125 |
+
"# embeds = OpenAIEmbedding(model=\"text-embedding-ada-002\", mode=\"similarity\")\n",
|
126 |
+
"\n",
|
127 |
"# Build index / generate embeddings using OpenAI.\n",
|
128 |
+
"index = VectorStoreIndex(nodes=nodes, show_progress=True, use_async=True, storage_context=storage_context, embed_model=embeds, insert_batch_size=3000,)"
|
129 |
]
|
130 |
},
|
131 |
{
|
132 |
"cell_type": "code",
|
133 |
+
"execution_count": null,
|
134 |
"metadata": {},
|
135 |
"outputs": [],
|
136 |
"source": [
|
137 |
+
"from llama_index.llms.openai import OpenAI\n",
|
138 |
+
"\n",
|
139 |
+
"llm = OpenAI(temperature=0, model=\"gpt-3.5-turbo-0125\", max_tokens=None)\n",
|
140 |
+
"query_engine = index.as_query_engine(llm=llm, similarity_top_k=5, embed_model=embeds)"
|
141 |
]
|
142 |
},
|
143 |
{
|
144 |
"cell_type": "code",
|
145 |
+
"execution_count": null,
|
146 |
"metadata": {},
|
147 |
"outputs": [],
|
148 |
"source": [
|
149 |
+
"res = query_engine.query(\"What is the LLama model?\")"
|
150 |
]
|
151 |
},
|
152 |
{
|
153 |
"cell_type": "code",
|
154 |
+
"execution_count": null,
|
155 |
"metadata": {},
|
156 |
+
"outputs": [],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
"source": [
|
158 |
"res.response"
|
159 |
]
|
160 |
},
|
161 |
{
|
162 |
"cell_type": "code",
|
163 |
+
"execution_count": null,
|
164 |
"metadata": {},
|
165 |
+
"outputs": [],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
"source": [
|
167 |
"for src in res.source_nodes:\n",
|
168 |
" print(\"Node ID\\t\", src.node_id)\n",
|
169 |
" print(\"Title\\t\", src.metadata['title'])\n",
|
170 |
" print(\"Text\\t\", src.text)\n",
|
171 |
" print(\"Score\\t\", src.score)\n",
|
172 |
+
" print(\"Metadata\\t\", src.metadata) \n",
|
173 |
" print(\"-_\"*20)"
|
174 |
]
|
175 |
},
|
|
|
182 |
},
|
183 |
{
|
184 |
"cell_type": "code",
|
185 |
+
"execution_count": 1,
|
186 |
"metadata": {},
|
187 |
"outputs": [],
|
188 |
"source": [
|
189 |
"import chromadb\n",
|
190 |
"from llama_index.vector_stores.chroma import ChromaVectorStore\n",
|
191 |
"# Create your index\n",
|
192 |
+
"db2 = chromadb.PersistentClient(path=\"./ai-tutor-db\")\n",
|
193 |
"chroma_collection = db2.get_or_create_collection(\"ai-tutor-db\")\n",
|
194 |
"vector_store = ChromaVectorStore(chroma_collection=chroma_collection)"
|
195 |
]
|
196 |
},
|
197 |
{
|
198 |
"cell_type": "code",
|
199 |
+
"execution_count": 2,
|
200 |
"metadata": {},
|
201 |
"outputs": [],
|
202 |
"source": [
|
|
|
207 |
},
|
208 |
{
|
209 |
"cell_type": "code",
|
210 |
+
"execution_count": 8,
|
211 |
"metadata": {},
|
212 |
"outputs": [],
|
213 |
"source": [
|
214 |
+
"from llama_index.embeddings.openai import OpenAIEmbedding\n",
|
215 |
+
"from llama_index.llms.openai import OpenAI\n",
|
216 |
+
"\n",
|
217 |
+
"llm = OpenAI(temperature=0, model=\"gpt-3.5-turbo-0125\", max_tokens=None)\n",
|
218 |
+
"embeds = OpenAIEmbedding(model=\"text-embedding-3-large\", mode=\"text_search\")\n",
|
219 |
+
"query_engine = index.as_query_engine(llm=llm, similarity_top_k=5, embed_model=embeds)"
|
220 |
]
|
221 |
},
|
222 |
{
|
223 |
"cell_type": "code",
|
224 |
+
"execution_count": 11,
|
225 |
"metadata": {},
|
226 |
"outputs": [],
|
227 |
"source": [
|
228 |
+
"res = query_engine.query(\"What is the LLama model?\")"
|
229 |
]
|
230 |
},
|
231 |
{
|
232 |
"cell_type": "code",
|
233 |
+
"execution_count": 12,
|
234 |
"metadata": {},
|
235 |
"outputs": [
|
236 |
{
|
237 |
"data": {
|
238 |
"text/plain": [
|
239 |
+
"'The Llama model is a new family of pre-trained and finetuned models released by Meta in mid-July. It includes different sizes such as 7B, 13B, and 70B, with corresponding papers describing their characteristics and learning process. The models are based on the standard transformer architecture and utilize techniques like RMSNorm normalization, SwiGLU activation, and rotatory positional embedding. The 70B model specifically applies the grouped-query attention (GQA) technique to speed up inference.'"
|
240 |
]
|
241 |
},
|
242 |
+
"execution_count": 12,
|
243 |
"metadata": {},
|
244 |
"output_type": "execute_result"
|
245 |
}
|
|
|
250 |
},
|
251 |
{
|
252 |
"cell_type": "code",
|
253 |
+
"execution_count": 13,
|
254 |
"metadata": {},
|
255 |
"outputs": [
|
256 |
{
|
257 |
"name": "stdout",
|
258 |
"output_type": "stream",
|
259 |
"text": [
|
260 |
+
"Node ID\t 7307e8a4-c4bd-4992-a68c-5230340f01c7\n",
|
261 |
+
"Source\t hf_transformers\n",
|
262 |
+
"Title\t Train\n",
|
263 |
+
"Text\t ged” arrays, so every tokenized sample would have to be padded to the length of the longest sample in the whole\n",
|
264 |
+
"dataset. That’s going to make your array even bigger, and all those padding tokens will slow down training too! Loading data as a tf.data.Dataset If you want to avoid slowing down training, you can load your data as a tf.data.Dataset instead. Although you can write your own\n",
|
265 |
+
"tf.data pipeline if you want, we have two convenience methods for doing this: prepare_tf_dataset(): This is the method we recommend in most cases. Because it is a method\n",
|
266 |
+
"on your model, it can inspect the model to automatically figure out which columns are usable as model inputs, and\n",
|
267 |
+
"discard the others to make a simpler, more performant dataset. to_tf_dataset: This method is more low-level, and is useful when you want to exactly control how\n",
|
268 |
+
"your dataset is created, by specifying exactly which columns and label_cols to include. Before you can use prepare_tf_dataset(), you will need to add the\n",
|
269 |
+
"Score\t 0.5175680124550022\n",
|
270 |
+
"-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
|
271 |
+
"Node ID\t 346a1018-8b33-4d83-b78f-2ba1b94f5e3b\n",
|
272 |
+
"Source\t openai\n",
|
273 |
+
"Title\t Researcher Access Program\n",
|
274 |
+
"Text\t There are a number of research directions we are excited to explore with the OpenAI API. If you are interested in the opportunity for subsidized access, please provide us with details about your research use case on the Researcher Access Program application.In particular, we consider the following to be especially important directions, though you are free to craft your own direction:Alignment: How can we understand what objective, if any, a model is best understood as pursuing? How do we increase the extent to which that objective is aligned with human preferences, such as via prompt design or fine-tuning?Fairness and representation: How should performance criteria be established for fairness and representation in language models? How can language models be improved in order to effectively support the goals of fairness and representation in specific, deployed contexts?Interdisciplinary research: How can AI development draw on insights from other disciplines such as philosophy, cognitive science, and sociolinguistics?Interpretability and transparency: How do these models work, mechanistically? Can we identify what concepts they're using, or extract latent knowledge from the model, make inferences about the training procedure, or predict surprising future behavior?Misuse potential: How can systems like the API be misused? What sorts of 'red teaming' approaches can we develop to help us and other AI developers think about responsibly deploying technologies like this?Model exploration: Models like those served by the API have a variety of capabilities which we have yet to explore. We're excited by investigations in many areas including model limitations, linguistic properties, commonsense reasoning, and potential uses for many other problems.Robustness: Generative models have uneven capability surfaces, with the potential for surprisingly strong and surprisingly weak areas of capability. How robust are large generative models to 'natural' perturbations in the prompt, such as phrasing the same idea in different ways or with or without typos? Can we predict the kinds of domains and tasks for which large generative models are more likely to be robust (or not robust), and how does this relate to the training data? Are there techniques we can use to predict and mitigate worst-case behavior? How can robustness be measured in the context of few-shot learning (e.g., across variations in prompts)? Can we train models so that they satisfy safety properties with a very high level of reliability, even under adversarial inputs?Please note that due to a high volume of requests, it takes time for us to review these applications and not all research will be prioritized for subsidy. We will only be in touch if your application is selected for subsidy.\n",
|
275 |
+
"Score\t 0.5129222370072439\n",
|
276 |
+
"-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
|
277 |
+
"Node ID\t ff0f2362-ddf7-4116-ac38-465dae37886a\n",
|
278 |
"Source\t towards_ai\n",
|
279 |
+
"Title\t Fine-Tuning a Llama-2 7B Model for Python Code Generation\n",
|
280 |
+
"Text\t New Llama-2 model In mid-July, Meta released its new family of pre-trained and finetuned models called Llama-2, with an open source and commercial character to facilitate its use and expansion. The base model was released with a chat version and sizes 7B, 13B, and 70B. Together with the models, the corresponding papers were published describing their characteristics and relevant points of the learning process, which provide very interesting information on the subject. For pre-training, 40% more tokens were used, reaching 2T, the context length was doubled and the grouped-query attention (GQA) technique was applied to speed up inference on the heavier 70B model. On the standard transformer architecture, RMSNorm normalization, SwiGLU activation, and rotatory positional embedding are used, the context length reaches 4096 tokens, and an Adam optimizer is applied with a cosine learning rate schedule, a weight decay of 0.1 and gradient clipping. \n",
|
281 |
+
"Score\t 0.49847282129286796\n",
|
282 |
+
"-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
|
283 |
+
"Node ID\t b0449da9-480c-48ea-80a3-35cfd84dbb48\n",
|
284 |
+
"Source\t hf_transformers\n",
|
285 |
+
"Title\t LayoutLMv2Tokenizer\n",
|
286 |
+
"Text\t class transformers.LayoutLMv2Tokenizer < source > ( vocab_file do_lower_case = True do_basic_tokenize = True never_split = None unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' cls_token_box = [0, 0, 0, 0] sep_token_box = [1000, 1000, 1000, 1000] pad_token_box = [0, 0, 0, 0] pad_token_label = -100 only_label_first_subword = True tokenize_chinese_chars = True strip_accents = None model_max_length: int = 512 additional_special_tokens: typing.Optional[typing.List[str]] = None **kwargs ) Construct a LayoutLMv2 tokenizer. Based on WordPiece. LayoutLMv2Tokenizer can be used to turn words, word-level\n",
|
287 |
+
"bounding boxes and optional word labels to token-level input_ids, attention_mask, token_type_ids, bbox, and\n",
|
288 |
+
"optional labels (for token classification). This tokenizer inherits from PreTrainedTokenizer which contains most of the main methods. Users should refer to\n",
|
289 |
+
"this superclass for more information regarding those methods. LayoutLM\n",
|
290 |
+
"Score\t 0.488783381968426\n",
|
291 |
"-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n",
|
292 |
+
"Node ID\t bdb45412-1d60-4c22-9de7-a3a469ac675a\n",
|
293 |
"Source\t hf_transformers\n",
|
294 |
+
"Title\t Train\n",
|
295 |
+
"Text\t tokenizer outputs to your dataset as columns, as shown in\n",
|
296 |
+
"the following code sample: Copied def tokenize_dataset(data):\n",
|
297 |
+
" # Keys of the returned dictionary will be added to the dataset as columns\n",
|
298 |
+
" return tokenizer(data[\"text\"])\n",
|
299 |
+
"dataset = dataset.map(tokenize_dataset) Remember that Hugging Face datasets are stored on disk by default, so this will not inflate your memory usage! Once the\n",
|
300 |
+
"columns have been added, you can stream batches from the dataset and add padding to each batch, which greatly\n",
|
301 |
+
"reduces the number of padding tokens compared to padding the entire dataset. Copied >>> tf_dataset = model.prepare_tf_dataset(dataset[\"train\"], batch_size=16, shuffle=True, tokenizer=tokenizer) Note that in the code sample above, you need to pass the tokenizer to prepare_tf_dataset so it can correctly pad batches as they’re loaded.\n",
|
302 |
+
"If all the samples in your dataset are the same length and no padding is necessary, you can skip this argument.\n",
|
303 |
+
"If you need to do something mor\n",
|
304 |
+
"Score\t 0.4819307254673903\n",
|
305 |
"-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n"
|
306 |
]
|
307 |
}
|
|
|
347 |
"name": "python",
|
348 |
"nbconvert_exporter": "python",
|
349 |
"pygments_lexer": "ipython3",
|
350 |
+
"version": "3.11.8"
|
351 |
}
|
352 |
},
|
353 |
"nbformat": 4,
|
scripts/gradio-ui.py
CHANGED
@@ -6,6 +6,8 @@ from datetime import datetime
|
|
6 |
import chromadb
|
7 |
from llama_index.vector_stores.chroma import ChromaVectorStore
|
8 |
from llama_index.core import VectorStoreIndex
|
|
|
|
|
9 |
import gradio as gr
|
10 |
from gradio.themes.utils import (
|
11 |
fonts,
|
@@ -51,12 +53,16 @@ mongo_db = (
|
|
51 |
else logger.warning("No mongodb uri found, you will not be able to save data.")
|
52 |
)
|
53 |
|
54 |
-
# Initialize
|
55 |
db2 = chromadb.PersistentClient(path="scripts/ai-tutor-db")
|
56 |
chroma_collection = db2.get_or_create_collection("ai-tutor-db")
|
57 |
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
|
58 |
index = VectorStoreIndex.from_vector_store(vector_store=vector_store)
|
59 |
-
|
|
|
|
|
|
|
|
|
60 |
|
61 |
|
62 |
AVAILABLE_SOURCES_UI = [
|
@@ -148,7 +154,7 @@ def format_sources(completion) -> str:
|
|
148 |
"📝 Here are the sources I used to answer your question:\n\n{documents}\n\n{footnote}"
|
149 |
)
|
150 |
document_template: str = (
|
151 |
-
"[🔗 {source}: {title}]({url}), relevance: {score:2.1f}
|
152 |
)
|
153 |
|
154 |
documents = "\n".join(
|
@@ -157,7 +163,7 @@ def format_sources(completion) -> str:
|
|
157 |
title=src.metadata["title"],
|
158 |
score=src.score,
|
159 |
source=display_source_to_ui.get(
|
160 |
-
src.metadata["
|
161 |
),
|
162 |
url=src.metadata["url"],
|
163 |
)
|
|
|
6 |
import chromadb
|
7 |
from llama_index.vector_stores.chroma import ChromaVectorStore
|
8 |
from llama_index.core import VectorStoreIndex
|
9 |
+
from llama_index.embeddings.openai import OpenAIEmbedding
|
10 |
+
from llama_index.llms.openai import OpenAI
|
11 |
import gradio as gr
|
12 |
from gradio.themes.utils import (
|
13 |
fonts,
|
|
|
53 |
else logger.warning("No mongodb uri found, you will not be able to save data.")
|
54 |
)
|
55 |
|
56 |
+
# Initialize vector store and index
|
57 |
db2 = chromadb.PersistentClient(path="scripts/ai-tutor-db")
|
58 |
chroma_collection = db2.get_or_create_collection("ai-tutor-db")
|
59 |
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
|
60 |
index = VectorStoreIndex.from_vector_store(vector_store=vector_store)
|
61 |
+
|
62 |
+
# Initialize query engine
|
63 |
+
llm = OpenAI(temperature=0, model="gpt-3.5-turbo-0125", max_tokens=None)
|
64 |
+
embeds = OpenAIEmbedding(model="text-embedding-3-large", mode="text_search")
|
65 |
+
query_engine = index.as_query_engine(llm=llm, similarity_top_k=5, embed_model=embeds)
|
66 |
|
67 |
|
68 |
AVAILABLE_SOURCES_UI = [
|
|
|
154 |
"📝 Here are the sources I used to answer your question:\n\n{documents}\n\n{footnote}"
|
155 |
)
|
156 |
document_template: str = (
|
157 |
+
"[🔗 {source}: {title}]({url}), relevance: {score:2.1f}" # Adjusted to include URL and format score as relevance
|
158 |
)
|
159 |
|
160 |
documents = "\n".join(
|
|
|
163 |
title=src.metadata["title"],
|
164 |
score=src.score,
|
165 |
source=display_source_to_ui.get(
|
166 |
+
src.metadata["source"], src.metadata["source"]
|
167 |
),
|
168 |
url=src.metadata["url"],
|
169 |
)
|