HelloLlamaCloud.ipynb 14.1 KB
Newer Older
Rayyyyy's avatar
Rayyyyy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1c1ea03a-cc69-45b0-80d3-664e48ca6831",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/meta-llama/llama-recipes/blob/main/recipes/use_cases/RAG/HelloLlamaCloud.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
    "\n",
    "## This demo app shows:\n",
    "* How to run Llama 3 in the cloud hosted on Replicate\n",
    "* How to use LangChain to ask Llama general questions and follow up questions\n",
    "* How to use LangChain to load a recent web page - Hugging Face's [blog post on Llama 3](https://huggingface.co/blog/llama3) - and chat about it. This is the well known RAG (Retrieval Augmented Generation) method to let LLM such as Llama 3 be able to answer questions about the data not publicly available when Llama 3 was trained, or about your own data. RAG is one way to prevent LLM's hallucination\n",
    "\n",
    "**Note** We will be using [Replicate](https://replicate.com/meta/meta-llama-3-8b-instruct) to run the examples here. You will need to first sign in with Replicate with your github account, then create a free API token [here](https://replicate.com/account/api-tokens) that you can use for a while. You can also use other Llama 3 cloud providers such as [Groq](https://console.groq.com/), [Together](https://api.together.xyz/playground/language/meta-llama/Llama-3-8b-hf), or [Anyscale](https://app.endpoints.anyscale.com/playground) - see Section 2 of the Getting to Know Llama [notebook](https://github.com/meta-llama/llama-recipes/blob/main/recipes/quickstart/Getting_to_know_Llama.ipynb) for more information."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61dde626",
   "metadata": {},
   "source": [
    "Let's start by installing the necessary packages:\n",
    "- sentence-transformers for text embeddings\n",
    "- FAISS gives us database capabilities \n",
    "- LangChai provides necessary RAG tools for this demo"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c608df5",
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install langchain\n",
    "!pip install sentence-transformers\n",
    "!pip install faiss-cpu\n",
    "!pip install bs4\n",
    "!pip install replicate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9c5546a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from getpass import getpass\n",
    "import os\n",
    "\n",
    "REPLICATE_API_TOKEN = getpass()\n",
    "os.environ[\"REPLICATE_API_TOKEN\"] = REPLICATE_API_TOKEN\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e8870c1",
   "metadata": {},
   "source": [
    "Next we call the Llama 3 8b chat model from Replicate. You can also use Llama 3 70b model by replacing the `model` name with \"meta/meta-llama-3-70b-instruct\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad536adb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.llms import Replicate\n",
    "llm = Replicate(\n",
    "    model=\"meta/meta-llama-3-8b-instruct\",\n",
    "    model_kwargs={\"temperature\": 0.0, \"top_p\": 1, \"max_new_tokens\":500}\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd207c80",
   "metadata": {},
   "source": [
    "With the model set up, you are now ready to ask some questions. Here is an example of the simplest way to ask the model some general questions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "493a7148",
   "metadata": {},
   "outputs": [],
   "source": [
    "question = \"who wrote the book Innovator's dilemma?\"\n",
    "answer = llm.invoke(question)\n",
    "print(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f315f000",
   "metadata": {},
   "source": [
    "We will then try to follow up the response with a question asking for more information on the book. \n",
    "\n",
    "Since the chat history is not passed on Llama doesn't have the context and doesn't know this is more about the book thus it treats this as new query.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9b5c8676",
   "metadata": {},
   "outputs": [],
   "source": [
    "# chat history not passed so Llama doesn't have the context and doesn't know this is more about the book\n",
    "followup = \"tell me more\"\n",
    "followup_answer = llm.invoke(followup)\n",
    "print(followup_answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9aeaffc7",
   "metadata": {},
   "source": [
    "To get around this we will need to provide the model with history of the chat. \n",
    "\n",
    "To do this, we will use  [`ConversationBufferMemory`](https://python.langchain.com/docs/modules/memory/types/buffer) to pass the chat history to the model and give it the capability to handle follow up questions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5428ca27",
   "metadata": {},
   "outputs": [],
   "source": [
    "# using ConversationBufferMemory to pass memory (chat history) for follow up questions\n",
    "from langchain.chains import ConversationChain\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "memory = ConversationBufferMemory()\n",
    "conversation = ConversationChain(\n",
    "    llm=llm, \n",
    "    memory = memory,\n",
    "    verbose=False\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3e9af5f",
   "metadata": {},
   "source": [
    "Once this is set up, let us repeat the steps from before and ask the model a simple question.\n",
    "\n",
    "Then we pass the question and answer back into the model for context along with the follow up question."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "baee2d22",
   "metadata": {},
   "outputs": [],
   "source": [
    "# restart from the original question\n",
    "answer = conversation.predict(input=question)\n",
    "print(answer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c7d67a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# pass context (previous question and answer) along with the follow up \"tell me more\" to Llama who now knows more of what\n",
    "memory.save_context({\"input\": question},\n",
    "                    {\"output\": answer})\n",
    "followup_answer = conversation.predict(input=followup)\n",
    "print(followup_answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc436163",
   "metadata": {},
   "source": [
    "Next, let's explore using Llama 3 to answer questions using documents for context. \n",
    "This gives us the ability to update Llama 3's knowledge thus giving it better context without needing to finetune. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5303d75",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.embeddings import HuggingFaceEmbeddings\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from langchain_community.document_loaders import WebBaseLoader\n",
    "import bs4\n",
    "\n",
    "loader = WebBaseLoader([\"https://huggingface.co/blog/llama3\"])\n",
    "docs = loader.load()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73b8268e",
   "metadata": {},
   "source": [
    "We need to store our document in a vector store. There are more than 30 vector stores (DBs) supported by LangChain. \n",
    "For this example we will use [FAISS](https://github.com/facebookresearch/faiss), a popular open source vector store by Facebook.\n",
    "For other vector stores especially if you need to store a large amount of data - see [here](https://python.langchain.com/docs/integrations/vectorstores).\n",
    "\n",
    "We will also import the HuggingFaceEmbeddings and RecursiveCharacterTextSplitter to assist in storing the documents."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eecb6a34",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Split the document into chunks with a specified chunk size\n",
    "text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)\n",
    "all_splits = text_splitter.split_documents(docs)\n",
    "\n",
    "# Store the document into a vector store with a specific embedding model\n",
    "vectorstore = FAISS.from_documents(all_splits, HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\"))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36d4a17c",
   "metadata": {},
   "source": [
    "To store the documents, we will need to split them into chunks using [`RecursiveCharacterTextSplitter`](https://python.langchain.com/docs/modules/data_connection/document_transformers/text_splitters/recursive_text_splitter) and create vector representations of these chunks using [`HuggingFaceEmbeddings`](https://www.google.com/search?q=langchain+hugging+face+embeddings&sca_esv=572890011&ei=ARUoZaH4LuumptQP48ah2Ac&oq=langchian+hugg&gs_lp=Egxnd3Mtd2l6LXNlcnAiDmxhbmdjaGlhbiBodWdnKgIIADIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCjIHEAAYgAQYCkjeHlC5Cli5D3ABeAGQAQCYAV6gAb4CqgEBNLgBAcgBAPgBAcICChAAGEcY1gQYsAPiAwQYACBBiAYBkAYI&sclient=gws-wiz-serp) on them before storing them into our vector database. \n",
    "\n",
    "In general, you should use larger chuck sizes for highly structured text such as code and smaller size for less structured text. You may need to experiment with different chunk sizes and overlap values to find out the best numbers.\n",
    "\n",
    "We then use `RetrievalQA` to retrieve the documents from the vector database and give the model more context on Llama 3, thereby increasing its knowledge.\n",
    "\n",
    "For each question, LangChain performs a semantic similarity search of it in the vector db, then passes the search results as the context to Llama to answer the question."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00e3f72b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# use LangChain's RetrievalQA, to associate Llama 3 with the loaded documents stored in the vector db\n",
    "from langchain.chains import RetrievalQA\n",
    "\n",
    "qa_chain = RetrievalQA.from_chain_type(\n",
    "    llm,\n",
    "    retriever=vectorstore.as_retriever()\n",
    ")\n",
    "\n",
    "question = \"What's new with Llama 3?\"\n",
    "result = qa_chain({\"query\": question})\n",
    "print(result['result'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e63769a",
   "metadata": {},
   "source": [
    "Now, lets bring it all together by incorporating follow up questions.\n",
    "\n",
    "First we ask a follow up questions without giving the model context of the previous conversation. \n",
    "Without this context, the answer we get does not relate to our original question."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53f27473",
   "metadata": {},
   "outputs": [],
   "source": [
    "# no context passed so Llama 3 doesn't have enough context to answer so it lets its imagination go wild\n",
    "result = qa_chain({\"query\": \"Based on what architecture?\"})\n",
    "print(result['result'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "833221c0",
   "metadata": {},
   "source": [
    "As we did before, let us use the `ConversationalRetrievalChain` package to give the model context of our previous question so we can add follow up questions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "743644a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# use ConversationalRetrievalChain to pass chat history for follow up questions\n",
    "from langchain.chains import ConversationalRetrievalChain\n",
    "chat_chain = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), return_source_documents=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c3d1142",
   "metadata": {},
   "outputs": [],
   "source": [
    "# let's ask the original question What's new with Llama 3?\" again\n",
    "result = chat_chain({\"question\": question, \"chat_history\": []})\n",
    "print(result['answer'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b17f08f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# this time we pass chat history along with the follow up so good things should happen\n",
    "chat_history = [(question, result[\"answer\"])]\n",
    "followup = \"Based on what architecture?\"\n",
    "followup_answer = chat_chain({\"question\": followup, \"chat_history\": chat_history})\n",
    "print(followup_answer['answer'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95d22347",
   "metadata": {},
   "outputs": [],
   "source": [
    "# further follow ups can be made possible by updating chat_history like this:\n",
    "chat_history.append((followup, followup_answer[\"answer\"]))\n",
    "more_followup = \"What changes in vocabulary size?\"\n",
    "more_followup_answer = chat_chain({\"question\": more_followup, \"chat_history\": chat_history})\n",
    "print(more_followup_answer['answer'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62daf288-bfca-4853-b153-0d8c73412804",
   "metadata": {},
   "source": [
    "**Note:** If results can get cut off, you can set \"max_new_tokens\" in the Replicate call above to a larger number (like shown below) to avoid the cut off.\n",
    "\n",
    "```python\n",
    "model_kwargs={\"temperature\": 0.01, \"top_p\": 1, \"max_new_tokens\": 1000}\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cdbbfbc6-e784-4cc9-8bd8-7f11e16c9456",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}