File size: 21,608 Bytes
431621a |
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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "lcW6UWldWUMp"
},
"source": [
"# Open Source RAG - Leveraging Hugging Face Endpoints through LangChain\n",
"\n",
"In the following notebook we will dive into the world of Open Source models hosted on Hugging Face's [inference endpoints](https://ui.endpoints.huggingface.co/).\n",
"\n",
"The notebook will be broken into the following parts:\n",
"\n",
"- 🤝 Breakout Room #2:\n",
" 1. Install required libraries\n",
" 2. Set Environment Variables\n",
" 3. Creating LangChain components powered by the endpoints\n",
" 4. Creating a simple RAG pipeline with [LangChain v0.2.0](https://blog.langchain.dev/langchain-v02-leap-to-stability/)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-spIWt2J3Quk"
},
"source": [
"## Task 1: Install required libraries\n",
"\n",
"Now we've got to get our required libraries!\n",
"\n",
"We'll start with our `langchain` and `huggingface` dependencies.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"id": "EwGLnp31jXJj"
},
"outputs": [],
"source": [
"!pip install -qU langchain-huggingface langchain-community faiss-cpu"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "SpZTBLwK3TIz"
},
"source": [
"## Task 2: Set Environment Variables\n",
"\n",
"We'll need to set our `HF_TOKEN` so that we can send requests to our protected API endpoint.\n",
"\n",
"We'll also set-up our OpenAI API key, which we'll leverage later.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "NspG8I0XlFTt",
"outputId": "edbf992c-97c0-46b1-9b69-40651a5e60d1"
},
"outputs": [],
"source": [
"import os\n",
"import getpass\n",
"\n",
"os.environ[\"HF_TOKEN\"] = getpass.getpass(\"HuggingFace Write Token: \")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QMru14VBZAtw"
},
"source": [
"## Task 3: Creating LangChain components powered by the endpoints\n",
"\n",
"We're going to wrap our endpoints in LangChain components in order to leverage them, thanks to LCEL, as we would any other LCEL component!"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TGooehdzcmPb"
},
"source": [
"### HuggingFaceEndpoint for LLM\n",
"\n",
"We can use the `HuggingFaceEndpoint` found [here](https://github.com/langchain-ai/langchain/blob/master/libs/community/langchain_community/llms/huggingface_endpoint.py) to power our chain - let's look at how we would implement it."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"id": "N7u2Tu1FsURh"
},
"outputs": [],
"source": [
"YOUR_LLM_ENDPOINT_URL = \"https://ta8oebbz7gg0766a.us-east-1.aws.endpoints.huggingface.cloud\""
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "L3Cz6Mrnt2ku",
"outputId": "f23f611f-5f08-4332-a74c-5b8d8311d185"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/opt/homebrew/anaconda3/envs/llmops/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:139: LangChainDeprecationWarning: The class `HuggingFaceEndpoint` was deprecated in LangChain 0.0.37 and will be removed in 0.3. An updated version of the class exists in the langchain-huggingface package and should be used instead. To use it run `pip install -U langchain-huggingface` and import as `from langchain_huggingface import HuggingFaceEndpoint`.\n",
" warn_deprecated(\n",
"/opt/homebrew/anaconda3/envs/llmops/lib/python3.12/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",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"The token has not been saved to the git credentials helper. Pass `add_to_git_credential=True` in this function directly or `--add-to-git-credential` if using via `huggingface-cli` if you want to set the git credential as well.\n",
"Token is valid (permission: write).\n",
"Your token has been saved to /Users/maraka/.cache/huggingface/token\n",
"Login successful\n"
]
}
],
"source": [
"from langchain_community.llms import HuggingFaceEndpoint\n",
"\n",
"hf_llm = HuggingFaceEndpoint(\n",
" endpoint_url=f\"{YOUR_LLM_ENDPOINT_URL}\",\n",
" max_new_tokens=512,\n",
" top_k=10,\n",
" top_p=0.95,\n",
" typical_p=0.95,\n",
" temperature=0.01,\n",
" repetition_penalty=1.03,\n",
" huggingfacehub_api_token=os.environ[\"HF_TOKEN\"]\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fun4XrRxZK9n"
},
"source": [
"Now we can use our endpoint like we would any other LLM!"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 127
},
"id": "OFAbFT91Z8QV",
"outputId": "588714ad-da28-4330-801b-7121b6f17ccf"
},
"outputs": [
{
"data": {
"text/plain": [
"\" I hope you're having a great day! I just wanted to reach out and say hello. I've been thinking about you lately and wanted to see how you're doing. Is everything going well? Do you have any new updates or news you'd like to share? I'm always here to listen and support you in any way I can. Take care and talk to you soon!\\nI hope this message finds you well. I was just thinking about you and wanted to say hello. How have you been? Have you been up to anything exciting or new? I'd love to hear about it. If you have any time, I'd love to catch up and chat. Let me know if that sounds good to you.\\nI hope you're doing well. I was just thinking about you and wanted to reach out. It's been a while since we last spoke, and I was wondering how you've been. Have you been up to anything new or exciting? I'd love to hear about it. If you have some time, I'd love to catch up and chat. Let me know if that sounds good to you.\\nI hope you're doing well. I was just thinking about you and wanted to say hello. I know it's been a while since we last spoke, but I've been thinking about you and wanted to reach out. How have you been? Have you been up to anything new or exciting? I'd love to hear about it. If you have some time, I'd love to catch up and chat. Let me know if that sounds good to you.\\nI hope you're doing well. I was just thinking about you and wanted to say hello. I know it's been a while since we last spoke, but I've been thinking about you and wanted to reach out. How have you been? Have you been up to anything new or exciting? I'd love to hear about it. If you have some time, I'd love to catch up and chat. Let me know if that sounds good to you.\\nI hope you're doing well. I was just thinking about you and wanted to say hello. I know it's been a while since we last spoke, but I've been thinking about you and wanted to reach out. How have you been? Have you been up to anything new or exciting? I'd love to hear about it. If you have some time, I'd love to catch up and chat. Let me know if that sounds good to you.\\nI hope you're doing well. I was just\""
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"hf_llm.invoke(\"Hello, how are you?\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ngH3fhw4aQ8T"
},
"source": [
"Now we can add a RAG-style prompt using Llama 3 Instruct's prompt templating!"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"id": "zdvv4JmkzEtj"
},
"outputs": [],
"source": [
"from langchain_core.prompts import PromptTemplate\n",
"\n",
"RAG_PROMPT_TEMPLATE = \"\"\"\\\n",
"<|start_header_id|>system<|end_header_id|>\n",
"You are a helpful assistant. You answer user questions based on provided context. If you can't answer the question with the provided context, say you don't know.<|eot_id|>\n",
"\n",
"<|start_header_id|>user<|end_header_id|>\n",
"User Query:\n",
"{query}\n",
"\n",
"Context:\n",
"{context}<|eot_id|>\n",
"\n",
"<|start_header_id|>assistant<|end_header_id|>\n",
"\"\"\"\n",
"\n",
"rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Oe0Qrzn4adzh"
},
"source": [
"Let's create a simple LCEL chain using our prompt template Runnable and our LLM Runnable."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"id": "CE4djpxM0-Fg"
},
"outputs": [],
"source": [
"rag_chain = rag_prompt | hf_llm"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"id": "PNwrLXqDxHDY",
"outputId": "f6803286-1aa5-488a-eea9-8bece68da7f5"
},
"outputs": [
{
"data": {
"text/plain": [
"'According to the context, Carl is 40 years old.'"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"rag_chain.invoke({\"query\" : \"Who old is Carl?\", \"context\" : \"Carl is a sweet dude, he's 40.\"})"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "emGw4-66aBfa"
},
"source": [
"### HuggingFaceInferenceAPIEmbeddings\n",
"\n",
"Now we can leverage the `HuggingFaceInferenceAPIEmbeddings` module in LangChain to connect to our Hugging Face Inference Endpoint hosted embedding model."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"id": "n9Q7e4Gnwe_C"
},
"outputs": [],
"source": [
"from langchain_huggingface.embeddings import HuggingFaceEndpointEmbeddings\n",
"\n",
"YOUR_EMBED_MODEL_URL = \"https://ropgl65i14toxmih.us-east-1.aws.endpoints.huggingface.cloud\"\n",
"\n",
"hf_embeddings = HuggingFaceEndpointEmbeddings(\n",
" model=f\"{YOUR_EMBED_MODEL_URL}\",\n",
" task=\"feature-extraction\",\n",
" huggingfacehub_api_token=os.environ[\"HF_TOKEN\"],\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YXYRBqbBayWb"
},
"source": [
"Let's build a simple cosine-similarity function to verify our endpoint is working as expected."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "lOP6LKr74RG8"
},
"outputs": [],
"source": [
"import numpy as np\n",
"from numpy.linalg import norm\n",
"\n",
"def cosine_similarity(phrase_1, phrase_2):\n",
" vec_1 = hf_embeddings.embed_documents([phrase_1])[0]\n",
" vec2_2 = hf_embeddings.embed_documents([phrase_2])[0]\n",
" return np.dot(vec_1, vec2_2) / (norm(vec_1) * norm(vec2_2))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "uGZNhxF2bVIr"
},
"source": [
"Let's try a few examples below!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "5o_cqEZ34f15",
"outputId": "d3eb4933-8842-4278-fe48-2dc15e430b60"
},
"outputs": [
{
"data": {
"text/plain": [
"0.8903063446222079"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cosine_similarity(\"I love my fluffy dog!\", \"I adore this furry puppy!\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "R1nsAV1n4w4a",
"outputId": "db53d783-4c87-404f-de67-fc1d01583e68"
},
"outputs": [
{
"data": {
"text/plain": [
"0.743020791930313"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cosine_similarity(\"I love my fluffy dog!\", \"Eating pizza is the worst! Yuck!\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iiz6vKMlbbP4"
},
"source": [
"## Task 4: Preparing Data!\n",
"\n",
"We'll start by loading some data from GitHub (Paul Graham's Essays) and then move to chunking them into manageable pieces!\n",
"\n",
"First - let's grab the repository where the files live."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "AkuzZben5Eqp",
"outputId": "eb8d39ae-fd70-4691-ddaa-1f8aa15f1c19"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Cloning into 'paul-graham-to-kindle'...\n",
"remote: Enumerating objects: 36, done.\u001b[K\n",
"remote: Counting objects: 100% (36/36), done.\u001b[K\n",
"remote: Compressing objects: 100% (33/33), done.\u001b[K\n",
"remote: Total 36 (delta 3), reused 31 (delta 1), pack-reused 0\u001b[K\n",
"Receiving objects: 100% (36/36), 2.35 MiB | 7.13 MiB/s, done.\n",
"Resolving deltas: 100% (3/3), done.\n"
]
}
],
"source": [
"!git clone https://github.com/dbredvick/paul-graham-to-kindle.git"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8prMk6R0bsYd"
},
"source": [
"Next - we can load them using LangChain!"
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {
"id": "K155zM7e53lt"
},
"outputs": [],
"source": [
"from langchain_community.document_loaders import TextLoader\n",
"\n",
"document_loader = TextLoader(\"./paul-graham-to-kindle/paul_graham_essays.txt\")\n",
"documents = document_loader.load()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5wYfo6_0bwVc"
},
"source": [
"Now, let's split them into 1000 character pieces."
]
},
{
"cell_type": "code",
"execution_count": 108,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "w-Gx_0iL6Ikc",
"outputId": "4cd1de4f-8a7d-4727-dc92-0ce3d321a82f"
},
"outputs": [
{
"data": {
"text/plain": [
"4265"
]
},
"execution_count": 108,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
"\n",
"text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)\n",
"split_documents = text_splitter.split_documents(documents)\n",
"len(split_documents)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d5HrkDhTb4i_"
},
"source": [
"Just the same as we would with OpenAI's embeddings model - we can instantiate our `FAISS` vector store with our documents and our `HuggingFaceEmbeddings` model!\n",
"\n",
"We'll need to take a few extra steps, though, due to a few limitations of the endpoint/FAISS.\n",
"\n",
"We'll start by embeddings our documents in batches of `32`.\n",
"\n",
"> NOTE: This process might take a while depending on the compute you assigned your embedding endpoint!"
]
},
{
"cell_type": "code",
"execution_count": 110,
"metadata": {
"id": "ucghQgRp6YXr"
},
"outputs": [],
"source": [
"from langchain_community.vectorstores import FAISS\n",
"\n",
"for i in range(0, len(split_documents), 32):\n",
" if i == 0:\n",
" vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)\n",
" continue\n",
" vectorstore.add_documents(split_documents[i:i+32])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "q07ZUp6Db_AO"
},
"source": [
"Next, we set up FAISS as a retriever."
]
},
{
"cell_type": "code",
"execution_count": 111,
"metadata": {
"id": "fXr-yrAq7h8V"
},
"outputs": [],
"source": [
"hf_retriever = vectorstore.as_retriever()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sYrW6FRecO7U"
},
"source": [
"## Task 5: Simple LCEL RAG Chain\n",
"\n",
"Now we can set up our LCEL RAG chain!\n",
"\n",
"> NOTE: We're not returning context for this example, and only returning the text output from the LLM."
]
},
{
"cell_type": "code",
"execution_count": 112,
"metadata": {
"id": "ffIzIlct8ISb"
},
"outputs": [],
"source": [
"from operator import itemgetter\n",
"from langchain.schema.output_parser import StrOutputParser\n",
"from langchain.schema.runnable import RunnablePassthrough\n",
"\n",
"lcel_rag_chain = {\"context\": itemgetter(\"query\") | hf_retriever, \"query\": itemgetter(\"query\")}| rag_prompt | hf_llm"
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 127
},
"id": "HOQfkEgb8nPH",
"outputId": "92601728-d001-43e2-e543-e714d66f4f4e"
},
"outputs": [
{
"data": {
"application/vnd.google.colaboratory.intrinsic+json": {
"type": "string"
},
"text/plain": [
"\"Based on the provided context, it seems that Paul Graham, the author, is discussing the shortcomings of Silicon Valley and suggesting ways to improve it. He mentions that the best part of Silicon Valley is not the physical buildings, but the people who make it Silicon Valley.\\n\\nHowever, he also criticizes the current state of Silicon Valley, saying that it's too far from San Francisco, has poor public transportation, and is plagued by strip development. He suggests that to create a better Silicon Valley, one should focus on designing a town that prioritizes public transportation, walkability, and bikeability, rather than car-centric development.\\n\\nSo, in summary, the best part of Silicon Valley, according to Paul Graham, is the people, but the area itself has many weaknesses that need to be addressed to make it a more desirable place for startups and innovators.\""
]
},
"execution_count": 114,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lcel_rag_chain.invoke({\"query\" : \"What is the best part of Silicon Valley?\"})"
]
}
],
"metadata": {
"colab": {
"provenance": [],
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"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.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
|