Spaces:
Sleeping
Sleeping
File size: 20,848 Bytes
ab110df | 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 | {
"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",
"> You don't need to run this cell if you're running the notebook locally."
]
},
{
"cell_type": "code",
"execution_count": 95,
"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": 1,
"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": 2,
"metadata": {
"id": "N7u2Tu1FsURh"
},
"outputs": [],
"source": [
"YOUR_LLM_ENDPOINT_URL = \"https://dcrebqe18cydo729.us-east-1.aws.endpoints.huggingface.cloud\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "L3Cz6Mrnt2ku",
"outputId": "f23f611f-5f08-4332-a74c-5b8d8311d185"
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_32142/1022838628.py:3: LangChainDeprecationWarning: The class `HuggingFaceEndpoint` was deprecated in LangChain 0.0.37 and will be removed in 1.0. An updated version of the class exists in the :class:`~langchain-huggingface package and should be used instead. To use it run `pip install -U :class:`~langchain-huggingface` and import as `from :class:`~langchain_huggingface import HuggingFaceEndpoint``.\n",
" hf_llm = HuggingFaceEndpoint(\n",
"Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured.\n"
]
}
],
"source": [
"from langchain_community.llms import HuggingFaceEndpoint\n",
"\n",
"hf_llm = HuggingFaceEndpoint(\n",
" endpoint_url=f\"{YOUR_LLM_ENDPOINT_URL}\",\n",
" task=\"text-generation\",\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",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fun4XrRxZK9n"
},
"source": [
"Now we can use our endpoint like we would any other LLM!"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 127
},
"id": "OFAbFT91Z8QV",
"outputId": "588714ad-da28-4330-801b-7121b6f17ccf"
},
"outputs": [
{
"data": {
"text/plain": [
"\" I am doing well, thanks for asking. I have been busy with work and other things, but I always make time for my blog. Today, I want to talk about something that is very important to me: mental health.\\nAs you may know, I have been open about my struggles with anxiety and depression in the past. It's not something that I like to talk about, but it's something that I feel is important to share in order to help others who may be going through similar struggles.\\nMental health is just as important as physical health, and it's something that we should all prioritize. Unfortunately, there is still a stigma surrounding mental health, and many people struggle to speak openly about their feelings and experiences.\\nThat's why I want to use my platform to raise awareness and promote understanding of mental health. I believe that by talking openly and honestly about our struggles, we can break down the stigma and create a more supportive and compassionate community.\\nSo, today I want to talk about something that I think is really important: self-care. Self-care is not just about taking a relaxing bath or getting a massage (although those things are great too!). It's about taking care of your mind, body, and spirit in a way that nourishes and supports your overall well-being.\\nFor me, self-care looks like taking time to meditate and practice mindfulness, reading books and articles that inspire and educate me, and spending time in nature. It also means being kind to myself and acknowledging when I need to take a break or seek help.\\nI want to encourage you to think about what self-care means to you. What activities make you feel good? What things do you need to do to take care of your mind, body, and spirit?\\nRemember, self-care is not a luxury, it's a necessity. By prioritizing our own well-being, we can live happier, healthier, and more fulfilling lives.\\nThank you for reading, and I hope you'll join me in prioritizing self-care and mental health. Let's work together to create a more supportive and compassionate community!\\nWhat are some self-care activities that you enjoy? Share with me in the comments below!\\nI'm so glad you're talking about mental health and self-care! It's such an important topic and one that needs to be discussed more openly. I've been practicing self-care for a while now, and it's made a huge difference in my life. For me, self-care looks like exercise, meditation, and spending time with loved ones. I also love reading\""
]
},
"execution_count": 4,
"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": 8,
"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": 9,
"metadata": {
"id": "CE4djpxM0-Fg"
},
"outputs": [],
"source": [
"rag_chain = rag_prompt | hf_llm"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 36
},
"id": "PNwrLXqDxHDY",
"outputId": "f6803286-1aa5-488a-eea9-8bece68da7f5"
},
"outputs": [
{
"data": {
"text/plain": [
"'Carl is 40 years old.'"
]
},
"execution_count": 10,
"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": 11,
"metadata": {
"id": "n9Q7e4Gnwe_C"
},
"outputs": [],
"source": [
"from langchain_huggingface.embeddings import HuggingFaceEndpointEmbeddings\n",
"\n",
"YOUR_EMBED_MODEL_URL = \"https://c87ybgo18epgba6d.us-east-1.aws.endpoints.huggingface.cloud\"\n",
"\n",
"hf_embeddings = HuggingFaceEndpointEmbeddings(\n",
" model=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": 12,
"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": 13,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "5o_cqEZ34f15",
"outputId": "d3eb4933-8842-4278-fe48-2dc15e430b60"
},
"outputs": [
{
"data": {
"text/plain": [
"0.8903063446222079"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cosine_similarity(\"I love my fluffy dog!\", \"I adore this furry puppy!\")"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "R1nsAV1n4w4a",
"outputId": "db53d783-4c87-404f-de67-fc1d01583e68"
},
"outputs": [
{
"data": {
"text/plain": [
"0.6667445107282148"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cosine_similarity(\"I love my fluffy dog!\", \"Trekking across the arctic is tough work.\")"
]
},
{
"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": 16,
"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 (from 0)\u001b[K\n",
"Receiving objects: 100% (36/36), 2.35 MiB | 13.80 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": 17,
"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": 18,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "w-Gx_0iL6Ikc",
"outputId": "4cd1de4f-8a7d-4727-dc92-0ce3d321a82f"
},
"outputs": [
{
"data": {
"text/plain": [
"4265"
]
},
"execution_count": 18,
"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": 20,
"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": 21,
"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": 22,
"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": 23,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 127
},
"id": "HOQfkEgb8nPH",
"outputId": "92601728-d001-43e2-e543-e714d66f4f4e"
},
"outputs": [
{
"data": {
"text/plain": [
"\"According to the provided context, the best part of Silicon Valley is its proximity to a top-notch university, such as Stanford, which acts as a magnet to attract the best people from around the world. Additionally, the area's public transportation system, although not perfect, is considered good by American standards. However, the author suggests that the area could be improved by designing a town that prioritizes trains, bicycles, and pedestrian-friendly infrastructure over cars.\""
]
},
"execution_count": 23,
"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": ".venv",
"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.9.21"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
|