Spaces:
Sleeping
Sleeping
initial push
Browse files- .env.sample +5 -0
- .gitignore +6 -0
- .python-version +1 -0
- Dockerfile +29 -0
- Open_Source_RAG_Leveraging_Hugging_Face_Endpoints_through_LangChain.ipynb +622 -0
- README.md +5 -7
- app.py +202 -0
- chainlit.md +1 -0
- data/paul_graham_essays.txt +0 -0
- pyproject.toml +22 -0
- solution_app.py +190 -0
- uv.lock +0 -0
.env.sample
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# !!! DO NOT UPDATE THIS FILE DIRECTLY. MAKE A COPY AND RENAME IT `.env` TO PROCEED !!! #
|
| 2 |
+
HF_LLM_ENDPOINT="YOUR_LLM_ENDPOINT_URL_HERE"
|
| 3 |
+
HF_EMBED_ENDPOINT="YOUR_EMBED_MODEL_ENDPOINT_URL_HERE"
|
| 4 |
+
HF_TOKEN="YOUR_HF_TOKEN_HERE"
|
| 5 |
+
# !!! DO NOT UPDATE THIS FILE DIRECTLY. MAKE A COPY AND RENAME IT `.env` TO PROCEED !!! #
|
.gitignore
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.env
|
| 2 |
+
__pycache__/
|
| 3 |
+
.chainlit
|
| 4 |
+
*.faiss
|
| 5 |
+
*.pkl
|
| 6 |
+
.files
|
.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.9
|
Dockerfile
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Get a distribution that has uv already installed
|
| 2 |
+
FROM ghcr.io/astral-sh/uv:python3.13-bookworm-slim
|
| 3 |
+
|
| 4 |
+
# Add user - this is the user that will run the app
|
| 5 |
+
# If you do not set user, the app will run as root (undesirable)
|
| 6 |
+
RUN useradd -m -u 1000 user
|
| 7 |
+
USER user
|
| 8 |
+
|
| 9 |
+
# Set the home directory and path
|
| 10 |
+
ENV HOME=/home/user \
|
| 11 |
+
PATH=/home/user/.local/bin:$PATH
|
| 12 |
+
|
| 13 |
+
ENV UVICORN_WS_PROTOCOL=websockets
|
| 14 |
+
|
| 15 |
+
# Set the working directory
|
| 16 |
+
WORKDIR $HOME/app
|
| 17 |
+
|
| 18 |
+
# Copy the app to the container
|
| 19 |
+
COPY --chown=user . $HOME/app
|
| 20 |
+
|
| 21 |
+
# Install the dependencies
|
| 22 |
+
# RUN uv sync --frozen
|
| 23 |
+
RUN uv sync
|
| 24 |
+
|
| 25 |
+
# Expose the port
|
| 26 |
+
EXPOSE 7860
|
| 27 |
+
|
| 28 |
+
# Run the app
|
| 29 |
+
CMD ["uv", "run", "chainlit", "run", "solution_app.py", "--host", "0.0.0.0", "--port", "7860"]
|
Open_Source_RAG_Leveraging_Hugging_Face_Endpoints_through_LangChain.ipynb
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {
|
| 6 |
+
"id": "lcW6UWldWUMp"
|
| 7 |
+
},
|
| 8 |
+
"source": [
|
| 9 |
+
"# Open Source RAG - Leveraging Hugging Face Endpoints through LangChain\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"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",
|
| 12 |
+
"\n",
|
| 13 |
+
"The notebook will be broken into the following parts:\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"- 🤝 Breakout Room #2:\n",
|
| 16 |
+
" 1. Install required libraries\n",
|
| 17 |
+
" 2. Set Environment Variables\n",
|
| 18 |
+
" 3. Creating LangChain components powered by the endpoints\n",
|
| 19 |
+
" 4. Creating a simple RAG pipeline with [LangChain v0.2.0](https://blog.langchain.dev/langchain-v02-leap-to-stability/)"
|
| 20 |
+
]
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "markdown",
|
| 24 |
+
"metadata": {
|
| 25 |
+
"id": "-spIWt2J3Quk"
|
| 26 |
+
},
|
| 27 |
+
"source": [
|
| 28 |
+
"## Task 1: Install required libraries\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"Now we've got to get our required libraries!\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"We'll start with our `langchain` and `huggingface` dependencies.\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"> You don't need to run this cell if you're running the notebook locally."
|
| 35 |
+
]
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"cell_type": "code",
|
| 39 |
+
"execution_count": 95,
|
| 40 |
+
"metadata": {
|
| 41 |
+
"id": "EwGLnp31jXJj"
|
| 42 |
+
},
|
| 43 |
+
"outputs": [],
|
| 44 |
+
"source": [
|
| 45 |
+
"#!pip install -qU langchain-huggingface langchain-community faiss-cpu"
|
| 46 |
+
]
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "markdown",
|
| 50 |
+
"metadata": {
|
| 51 |
+
"id": "SpZTBLwK3TIz"
|
| 52 |
+
},
|
| 53 |
+
"source": [
|
| 54 |
+
"## Task 2: Set Environment Variables\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"We'll need to set our `HF_TOKEN` so that we can send requests to our protected API endpoint.\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"We'll also set-up our OpenAI API key, which we'll leverage later.\n",
|
| 59 |
+
"\n"
|
| 60 |
+
]
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"execution_count": 1,
|
| 65 |
+
"metadata": {
|
| 66 |
+
"colab": {
|
| 67 |
+
"base_uri": "https://localhost:8080/"
|
| 68 |
+
},
|
| 69 |
+
"id": "NspG8I0XlFTt",
|
| 70 |
+
"outputId": "edbf992c-97c0-46b1-9b69-40651a5e60d1"
|
| 71 |
+
},
|
| 72 |
+
"outputs": [],
|
| 73 |
+
"source": [
|
| 74 |
+
"import os\n",
|
| 75 |
+
"import getpass\n",
|
| 76 |
+
"\n",
|
| 77 |
+
"os.environ[\"HF_TOKEN\"] = getpass.getpass(\"HuggingFace Write Token: \")"
|
| 78 |
+
]
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "markdown",
|
| 82 |
+
"metadata": {
|
| 83 |
+
"id": "QMru14VBZAtw"
|
| 84 |
+
},
|
| 85 |
+
"source": [
|
| 86 |
+
"## Task 3: Creating LangChain components powered by the endpoints\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"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!"
|
| 89 |
+
]
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"cell_type": "markdown",
|
| 93 |
+
"metadata": {
|
| 94 |
+
"id": "TGooehdzcmPb"
|
| 95 |
+
},
|
| 96 |
+
"source": [
|
| 97 |
+
"### HuggingFaceEndpoint for LLM\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"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."
|
| 100 |
+
]
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"execution_count": 2,
|
| 105 |
+
"metadata": {
|
| 106 |
+
"id": "N7u2Tu1FsURh"
|
| 107 |
+
},
|
| 108 |
+
"outputs": [],
|
| 109 |
+
"source": [
|
| 110 |
+
"YOUR_LLM_ENDPOINT_URL = \"https://dcrebqe18cydo729.us-east-1.aws.endpoints.huggingface.cloud\""
|
| 111 |
+
]
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"metadata": {
|
| 117 |
+
"colab": {
|
| 118 |
+
"base_uri": "https://localhost:8080/"
|
| 119 |
+
},
|
| 120 |
+
"id": "L3Cz6Mrnt2ku",
|
| 121 |
+
"outputId": "f23f611f-5f08-4332-a74c-5b8d8311d185"
|
| 122 |
+
},
|
| 123 |
+
"outputs": [
|
| 124 |
+
{
|
| 125 |
+
"name": "stderr",
|
| 126 |
+
"output_type": "stream",
|
| 127 |
+
"text": [
|
| 128 |
+
"/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",
|
| 129 |
+
" hf_llm = HuggingFaceEndpoint(\n",
|
| 130 |
+
"Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured.\n"
|
| 131 |
+
]
|
| 132 |
+
}
|
| 133 |
+
],
|
| 134 |
+
"source": [
|
| 135 |
+
"from langchain_community.llms import HuggingFaceEndpoint\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"hf_llm = HuggingFaceEndpoint(\n",
|
| 138 |
+
" endpoint_url=f\"{YOUR_LLM_ENDPOINT_URL}\",\n",
|
| 139 |
+
" task=\"text-generation\",\n",
|
| 140 |
+
" max_new_tokens=512,\n",
|
| 141 |
+
" top_k=10,\n",
|
| 142 |
+
" top_p=0.95,\n",
|
| 143 |
+
" typical_p=0.95,\n",
|
| 144 |
+
" temperature=0.01,\n",
|
| 145 |
+
" repetition_penalty=1.03,\n",
|
| 146 |
+
")"
|
| 147 |
+
]
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "markdown",
|
| 151 |
+
"metadata": {
|
| 152 |
+
"id": "fun4XrRxZK9n"
|
| 153 |
+
},
|
| 154 |
+
"source": [
|
| 155 |
+
"Now we can use our endpoint like we would any other LLM!"
|
| 156 |
+
]
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"cell_type": "code",
|
| 160 |
+
"execution_count": 4,
|
| 161 |
+
"metadata": {
|
| 162 |
+
"colab": {
|
| 163 |
+
"base_uri": "https://localhost:8080/",
|
| 164 |
+
"height": 127
|
| 165 |
+
},
|
| 166 |
+
"id": "OFAbFT91Z8QV",
|
| 167 |
+
"outputId": "588714ad-da28-4330-801b-7121b6f17ccf"
|
| 168 |
+
},
|
| 169 |
+
"outputs": [
|
| 170 |
+
{
|
| 171 |
+
"data": {
|
| 172 |
+
"text/plain": [
|
| 173 |
+
"\" 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\""
|
| 174 |
+
]
|
| 175 |
+
},
|
| 176 |
+
"execution_count": 4,
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"output_type": "execute_result"
|
| 179 |
+
}
|
| 180 |
+
],
|
| 181 |
+
"source": [
|
| 182 |
+
"hf_llm.invoke(\"Hello, how are you?\")"
|
| 183 |
+
]
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "markdown",
|
| 187 |
+
"metadata": {
|
| 188 |
+
"id": "ngH3fhw4aQ8T"
|
| 189 |
+
},
|
| 190 |
+
"source": [
|
| 191 |
+
"Now we can add a RAG-style prompt using Llama 3 Instruct's prompt templating!"
|
| 192 |
+
]
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"execution_count": 8,
|
| 197 |
+
"metadata": {
|
| 198 |
+
"id": "zdvv4JmkzEtj"
|
| 199 |
+
},
|
| 200 |
+
"outputs": [],
|
| 201 |
+
"source": [
|
| 202 |
+
"from langchain_core.prompts import PromptTemplate\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"RAG_PROMPT_TEMPLATE = \"\"\"\\\n",
|
| 205 |
+
"<|start_header_id|>system<|end_header_id|>\n",
|
| 206 |
+
"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",
|
| 207 |
+
"\n",
|
| 208 |
+
"<|start_header_id|>user<|end_header_id|>\n",
|
| 209 |
+
"User Query:\n",
|
| 210 |
+
"{query}\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"Context:\n",
|
| 213 |
+
"{context}<|eot_id|>\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"<|start_header_id|>assistant<|end_header_id|>\n",
|
| 216 |
+
"\"\"\"\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)"
|
| 219 |
+
]
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "markdown",
|
| 223 |
+
"metadata": {
|
| 224 |
+
"id": "Oe0Qrzn4adzh"
|
| 225 |
+
},
|
| 226 |
+
"source": [
|
| 227 |
+
"Let's create a simple LCEL chain using our prompt template Runnable and our LLM Runnable."
|
| 228 |
+
]
|
| 229 |
+
},
|
| 230 |
+
{
|
| 231 |
+
"cell_type": "code",
|
| 232 |
+
"execution_count": 9,
|
| 233 |
+
"metadata": {
|
| 234 |
+
"id": "CE4djpxM0-Fg"
|
| 235 |
+
},
|
| 236 |
+
"outputs": [],
|
| 237 |
+
"source": [
|
| 238 |
+
"rag_chain = rag_prompt | hf_llm"
|
| 239 |
+
]
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"execution_count": 10,
|
| 244 |
+
"metadata": {
|
| 245 |
+
"colab": {
|
| 246 |
+
"base_uri": "https://localhost:8080/",
|
| 247 |
+
"height": 36
|
| 248 |
+
},
|
| 249 |
+
"id": "PNwrLXqDxHDY",
|
| 250 |
+
"outputId": "f6803286-1aa5-488a-eea9-8bece68da7f5"
|
| 251 |
+
},
|
| 252 |
+
"outputs": [
|
| 253 |
+
{
|
| 254 |
+
"data": {
|
| 255 |
+
"text/plain": [
|
| 256 |
+
"'Carl is 40 years old.'"
|
| 257 |
+
]
|
| 258 |
+
},
|
| 259 |
+
"execution_count": 10,
|
| 260 |
+
"metadata": {},
|
| 261 |
+
"output_type": "execute_result"
|
| 262 |
+
}
|
| 263 |
+
],
|
| 264 |
+
"source": [
|
| 265 |
+
"rag_chain.invoke({\"query\" : \"Who old is Carl?\", \"context\" : \"Carl is a sweet dude, he's 40.\"})"
|
| 266 |
+
]
|
| 267 |
+
},
|
| 268 |
+
{
|
| 269 |
+
"cell_type": "markdown",
|
| 270 |
+
"metadata": {
|
| 271 |
+
"id": "emGw4-66aBfa"
|
| 272 |
+
},
|
| 273 |
+
"source": [
|
| 274 |
+
"### HuggingFaceInferenceAPIEmbeddings\n",
|
| 275 |
+
"\n",
|
| 276 |
+
"Now we can leverage the `HuggingFaceInferenceAPIEmbeddings` module in LangChain to connect to our Hugging Face Inference Endpoint hosted embedding model."
|
| 277 |
+
]
|
| 278 |
+
},
|
| 279 |
+
{
|
| 280 |
+
"cell_type": "code",
|
| 281 |
+
"execution_count": 11,
|
| 282 |
+
"metadata": {
|
| 283 |
+
"id": "n9Q7e4Gnwe_C"
|
| 284 |
+
},
|
| 285 |
+
"outputs": [],
|
| 286 |
+
"source": [
|
| 287 |
+
"from langchain_huggingface.embeddings import HuggingFaceEndpointEmbeddings\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"YOUR_EMBED_MODEL_URL = \"https://c87ybgo18epgba6d.us-east-1.aws.endpoints.huggingface.cloud\"\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"hf_embeddings = HuggingFaceEndpointEmbeddings(\n",
|
| 292 |
+
" model=YOUR_EMBED_MODEL_URL,\n",
|
| 293 |
+
" task=\"feature-extraction\",\n",
|
| 294 |
+
" huggingfacehub_api_token=os.environ[\"HF_TOKEN\"],\n",
|
| 295 |
+
")"
|
| 296 |
+
]
|
| 297 |
+
},
|
| 298 |
+
{
|
| 299 |
+
"cell_type": "markdown",
|
| 300 |
+
"metadata": {
|
| 301 |
+
"id": "YXYRBqbBayWb"
|
| 302 |
+
},
|
| 303 |
+
"source": [
|
| 304 |
+
"Let's build a simple cosine-similarity function to verify our endpoint is working as expected."
|
| 305 |
+
]
|
| 306 |
+
},
|
| 307 |
+
{
|
| 308 |
+
"cell_type": "code",
|
| 309 |
+
"execution_count": 12,
|
| 310 |
+
"metadata": {
|
| 311 |
+
"id": "lOP6LKr74RG8"
|
| 312 |
+
},
|
| 313 |
+
"outputs": [],
|
| 314 |
+
"source": [
|
| 315 |
+
"import numpy as np\n",
|
| 316 |
+
"from numpy.linalg import norm\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"def cosine_similarity(phrase_1, phrase_2):\n",
|
| 319 |
+
" vec_1 = hf_embeddings.embed_documents([phrase_1])[0]\n",
|
| 320 |
+
" vec2_2 = hf_embeddings.embed_documents([phrase_2])[0]\n",
|
| 321 |
+
" return np.dot(vec_1, vec2_2) / (norm(vec_1) * norm(vec2_2))"
|
| 322 |
+
]
|
| 323 |
+
},
|
| 324 |
+
{
|
| 325 |
+
"cell_type": "markdown",
|
| 326 |
+
"metadata": {
|
| 327 |
+
"id": "uGZNhxF2bVIr"
|
| 328 |
+
},
|
| 329 |
+
"source": [
|
| 330 |
+
"Let's try a few examples below!"
|
| 331 |
+
]
|
| 332 |
+
},
|
| 333 |
+
{
|
| 334 |
+
"cell_type": "code",
|
| 335 |
+
"execution_count": 13,
|
| 336 |
+
"metadata": {
|
| 337 |
+
"colab": {
|
| 338 |
+
"base_uri": "https://localhost:8080/"
|
| 339 |
+
},
|
| 340 |
+
"id": "5o_cqEZ34f15",
|
| 341 |
+
"outputId": "d3eb4933-8842-4278-fe48-2dc15e430b60"
|
| 342 |
+
},
|
| 343 |
+
"outputs": [
|
| 344 |
+
{
|
| 345 |
+
"data": {
|
| 346 |
+
"text/plain": [
|
| 347 |
+
"0.8903063446222079"
|
| 348 |
+
]
|
| 349 |
+
},
|
| 350 |
+
"execution_count": 13,
|
| 351 |
+
"metadata": {},
|
| 352 |
+
"output_type": "execute_result"
|
| 353 |
+
}
|
| 354 |
+
],
|
| 355 |
+
"source": [
|
| 356 |
+
"cosine_similarity(\"I love my fluffy dog!\", \"I adore this furry puppy!\")"
|
| 357 |
+
]
|
| 358 |
+
},
|
| 359 |
+
{
|
| 360 |
+
"cell_type": "code",
|
| 361 |
+
"execution_count": 15,
|
| 362 |
+
"metadata": {
|
| 363 |
+
"colab": {
|
| 364 |
+
"base_uri": "https://localhost:8080/"
|
| 365 |
+
},
|
| 366 |
+
"id": "R1nsAV1n4w4a",
|
| 367 |
+
"outputId": "db53d783-4c87-404f-de67-fc1d01583e68"
|
| 368 |
+
},
|
| 369 |
+
"outputs": [
|
| 370 |
+
{
|
| 371 |
+
"data": {
|
| 372 |
+
"text/plain": [
|
| 373 |
+
"0.6667445107282148"
|
| 374 |
+
]
|
| 375 |
+
},
|
| 376 |
+
"execution_count": 15,
|
| 377 |
+
"metadata": {},
|
| 378 |
+
"output_type": "execute_result"
|
| 379 |
+
}
|
| 380 |
+
],
|
| 381 |
+
"source": [
|
| 382 |
+
"cosine_similarity(\"I love my fluffy dog!\", \"Trekking across the arctic is tough work.\")"
|
| 383 |
+
]
|
| 384 |
+
},
|
| 385 |
+
{
|
| 386 |
+
"cell_type": "markdown",
|
| 387 |
+
"metadata": {
|
| 388 |
+
"id": "iiz6vKMlbbP4"
|
| 389 |
+
},
|
| 390 |
+
"source": [
|
| 391 |
+
"## Task 4: Preparing Data!\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"We'll start by loading some data from GitHub (Paul Graham's Essays) and then move to chunking them into manageable pieces!\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"First - let's grab the repository where the files live."
|
| 396 |
+
]
|
| 397 |
+
},
|
| 398 |
+
{
|
| 399 |
+
"cell_type": "code",
|
| 400 |
+
"execution_count": 16,
|
| 401 |
+
"metadata": {
|
| 402 |
+
"colab": {
|
| 403 |
+
"base_uri": "https://localhost:8080/"
|
| 404 |
+
},
|
| 405 |
+
"id": "AkuzZben5Eqp",
|
| 406 |
+
"outputId": "eb8d39ae-fd70-4691-ddaa-1f8aa15f1c19"
|
| 407 |
+
},
|
| 408 |
+
"outputs": [
|
| 409 |
+
{
|
| 410 |
+
"name": "stdout",
|
| 411 |
+
"output_type": "stream",
|
| 412 |
+
"text": [
|
| 413 |
+
"Cloning into 'paul-graham-to-kindle'...\n",
|
| 414 |
+
"remote: Enumerating objects: 36, done.\u001b[K\n",
|
| 415 |
+
"remote: Counting objects: 100% (36/36), done.\u001b[K\n",
|
| 416 |
+
"remote: Compressing objects: 100% (33/33), done.\u001b[K\n",
|
| 417 |
+
"remote: Total 36 (delta 3), reused 31 (delta 1), pack-reused 0 (from 0)\u001b[K\n",
|
| 418 |
+
"Receiving objects: 100% (36/36), 2.35 MiB | 13.80 MiB/s, done.\n",
|
| 419 |
+
"Resolving deltas: 100% (3/3), done.\n"
|
| 420 |
+
]
|
| 421 |
+
}
|
| 422 |
+
],
|
| 423 |
+
"source": [
|
| 424 |
+
"!git clone https://github.com/dbredvick/paul-graham-to-kindle.git"
|
| 425 |
+
]
|
| 426 |
+
},
|
| 427 |
+
{
|
| 428 |
+
"cell_type": "markdown",
|
| 429 |
+
"metadata": {
|
| 430 |
+
"id": "8prMk6R0bsYd"
|
| 431 |
+
},
|
| 432 |
+
"source": [
|
| 433 |
+
"Next - we can load them using LangChain!"
|
| 434 |
+
]
|
| 435 |
+
},
|
| 436 |
+
{
|
| 437 |
+
"cell_type": "code",
|
| 438 |
+
"execution_count": 17,
|
| 439 |
+
"metadata": {
|
| 440 |
+
"id": "K155zM7e53lt"
|
| 441 |
+
},
|
| 442 |
+
"outputs": [],
|
| 443 |
+
"source": [
|
| 444 |
+
"from langchain_community.document_loaders import TextLoader\n",
|
| 445 |
+
"\n",
|
| 446 |
+
"document_loader = TextLoader(\"./paul-graham-to-kindle/paul_graham_essays.txt\")\n",
|
| 447 |
+
"documents = document_loader.load()"
|
| 448 |
+
]
|
| 449 |
+
},
|
| 450 |
+
{
|
| 451 |
+
"cell_type": "markdown",
|
| 452 |
+
"metadata": {
|
| 453 |
+
"id": "5wYfo6_0bwVc"
|
| 454 |
+
},
|
| 455 |
+
"source": [
|
| 456 |
+
"Now, let's split them into 1000 character pieces."
|
| 457 |
+
]
|
| 458 |
+
},
|
| 459 |
+
{
|
| 460 |
+
"cell_type": "code",
|
| 461 |
+
"execution_count": 18,
|
| 462 |
+
"metadata": {
|
| 463 |
+
"colab": {
|
| 464 |
+
"base_uri": "https://localhost:8080/"
|
| 465 |
+
},
|
| 466 |
+
"id": "w-Gx_0iL6Ikc",
|
| 467 |
+
"outputId": "4cd1de4f-8a7d-4727-dc92-0ce3d321a82f"
|
| 468 |
+
},
|
| 469 |
+
"outputs": [
|
| 470 |
+
{
|
| 471 |
+
"data": {
|
| 472 |
+
"text/plain": [
|
| 473 |
+
"4265"
|
| 474 |
+
]
|
| 475 |
+
},
|
| 476 |
+
"execution_count": 18,
|
| 477 |
+
"metadata": {},
|
| 478 |
+
"output_type": "execute_result"
|
| 479 |
+
}
|
| 480 |
+
],
|
| 481 |
+
"source": [
|
| 482 |
+
"from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
|
| 483 |
+
"\n",
|
| 484 |
+
"text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)\n",
|
| 485 |
+
"split_documents = text_splitter.split_documents(documents)\n",
|
| 486 |
+
"len(split_documents)"
|
| 487 |
+
]
|
| 488 |
+
},
|
| 489 |
+
{
|
| 490 |
+
"cell_type": "markdown",
|
| 491 |
+
"metadata": {
|
| 492 |
+
"id": "d5HrkDhTb4i_"
|
| 493 |
+
},
|
| 494 |
+
"source": [
|
| 495 |
+
"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",
|
| 496 |
+
"\n",
|
| 497 |
+
"We'll need to take a few extra steps, though, due to a few limitations of the endpoint/FAISS.\n",
|
| 498 |
+
"\n",
|
| 499 |
+
"We'll start by embeddings our documents in batches of `32`.\n",
|
| 500 |
+
"\n",
|
| 501 |
+
"> NOTE: This process might take a while depending on the compute you assigned your embedding endpoint!"
|
| 502 |
+
]
|
| 503 |
+
},
|
| 504 |
+
{
|
| 505 |
+
"cell_type": "code",
|
| 506 |
+
"execution_count": 20,
|
| 507 |
+
"metadata": {
|
| 508 |
+
"id": "ucghQgRp6YXr"
|
| 509 |
+
},
|
| 510 |
+
"outputs": [],
|
| 511 |
+
"source": [
|
| 512 |
+
"from langchain_community.vectorstores import FAISS\n",
|
| 513 |
+
"\n",
|
| 514 |
+
"for i in range(0, len(split_documents), 32):\n",
|
| 515 |
+
" if i == 0:\n",
|
| 516 |
+
" vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)\n",
|
| 517 |
+
" continue\n",
|
| 518 |
+
" vectorstore.add_documents(split_documents[i:i+32])"
|
| 519 |
+
]
|
| 520 |
+
},
|
| 521 |
+
{
|
| 522 |
+
"cell_type": "markdown",
|
| 523 |
+
"metadata": {
|
| 524 |
+
"id": "q07ZUp6Db_AO"
|
| 525 |
+
},
|
| 526 |
+
"source": [
|
| 527 |
+
"Next, we set up FAISS as a retriever."
|
| 528 |
+
]
|
| 529 |
+
},
|
| 530 |
+
{
|
| 531 |
+
"cell_type": "code",
|
| 532 |
+
"execution_count": 21,
|
| 533 |
+
"metadata": {
|
| 534 |
+
"id": "fXr-yrAq7h8V"
|
| 535 |
+
},
|
| 536 |
+
"outputs": [],
|
| 537 |
+
"source": [
|
| 538 |
+
"hf_retriever = vectorstore.as_retriever()"
|
| 539 |
+
]
|
| 540 |
+
},
|
| 541 |
+
{
|
| 542 |
+
"cell_type": "markdown",
|
| 543 |
+
"metadata": {
|
| 544 |
+
"id": "sYrW6FRecO7U"
|
| 545 |
+
},
|
| 546 |
+
"source": [
|
| 547 |
+
"## Task 5: Simple LCEL RAG Chain\n",
|
| 548 |
+
"\n",
|
| 549 |
+
"Now we can set up our LCEL RAG chain!\n",
|
| 550 |
+
"\n",
|
| 551 |
+
"> NOTE: We're not returning context for this example, and only returning the text output from the LLM."
|
| 552 |
+
]
|
| 553 |
+
},
|
| 554 |
+
{
|
| 555 |
+
"cell_type": "code",
|
| 556 |
+
"execution_count": 22,
|
| 557 |
+
"metadata": {
|
| 558 |
+
"id": "ffIzIlct8ISb"
|
| 559 |
+
},
|
| 560 |
+
"outputs": [],
|
| 561 |
+
"source": [
|
| 562 |
+
"from operator import itemgetter\n",
|
| 563 |
+
"from langchain.schema.output_parser import StrOutputParser\n",
|
| 564 |
+
"from langchain.schema.runnable import RunnablePassthrough\n",
|
| 565 |
+
"\n",
|
| 566 |
+
"lcel_rag_chain = {\"context\": itemgetter(\"query\") | hf_retriever, \"query\": itemgetter(\"query\")}| rag_prompt | hf_llm"
|
| 567 |
+
]
|
| 568 |
+
},
|
| 569 |
+
{
|
| 570 |
+
"cell_type": "code",
|
| 571 |
+
"execution_count": 23,
|
| 572 |
+
"metadata": {
|
| 573 |
+
"colab": {
|
| 574 |
+
"base_uri": "https://localhost:8080/",
|
| 575 |
+
"height": 127
|
| 576 |
+
},
|
| 577 |
+
"id": "HOQfkEgb8nPH",
|
| 578 |
+
"outputId": "92601728-d001-43e2-e543-e714d66f4f4e"
|
| 579 |
+
},
|
| 580 |
+
"outputs": [
|
| 581 |
+
{
|
| 582 |
+
"data": {
|
| 583 |
+
"text/plain": [
|
| 584 |
+
"\"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.\""
|
| 585 |
+
]
|
| 586 |
+
},
|
| 587 |
+
"execution_count": 23,
|
| 588 |
+
"metadata": {},
|
| 589 |
+
"output_type": "execute_result"
|
| 590 |
+
}
|
| 591 |
+
],
|
| 592 |
+
"source": [
|
| 593 |
+
"lcel_rag_chain.invoke({\"query\" : \"What is the best part of Silicon Valley?\"})"
|
| 594 |
+
]
|
| 595 |
+
}
|
| 596 |
+
],
|
| 597 |
+
"metadata": {
|
| 598 |
+
"colab": {
|
| 599 |
+
"provenance": [],
|
| 600 |
+
"toc_visible": true
|
| 601 |
+
},
|
| 602 |
+
"kernelspec": {
|
| 603 |
+
"display_name": ".venv",
|
| 604 |
+
"language": "python",
|
| 605 |
+
"name": "python3"
|
| 606 |
+
},
|
| 607 |
+
"language_info": {
|
| 608 |
+
"codemirror_mode": {
|
| 609 |
+
"name": "ipython",
|
| 610 |
+
"version": 3
|
| 611 |
+
},
|
| 612 |
+
"file_extension": ".py",
|
| 613 |
+
"mimetype": "text/x-python",
|
| 614 |
+
"name": "python",
|
| 615 |
+
"nbconvert_exporter": "python",
|
| 616 |
+
"pygments_lexer": "ipython3",
|
| 617 |
+
"version": "3.9.21"
|
| 618 |
+
}
|
| 619 |
+
},
|
| 620 |
+
"nbformat": 4,
|
| 621 |
+
"nbformat_minor": 0
|
| 622 |
+
}
|
README.md
CHANGED
|
@@ -1,10 +1,8 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
-
---
|
| 9 |
-
|
| 10 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Demo : Using hugging face endpoints
|
| 3 |
+
emoji: 🐢
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: red
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
+
---
|
|
|
|
|
|
app.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import chainlit as cl
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from operator import itemgetter
|
| 5 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
| 6 |
+
from langchain_community.document_loaders import TextLoader
|
| 7 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 8 |
+
from langchain_community.vectorstores import FAISS
|
| 9 |
+
from langchain_huggingface import HuggingFaceEndpointEmbeddings
|
| 10 |
+
from langchain_core.prompts import PromptTemplate
|
| 11 |
+
from langchain.schema.output_parser import StrOutputParser
|
| 12 |
+
from langchain.schema.runnable import RunnablePassthrough
|
| 13 |
+
from langchain.schema.runnable.config import RunnableConfig
|
| 14 |
+
from tqdm.asyncio import tqdm_asyncio
|
| 15 |
+
import asyncio
|
| 16 |
+
from tqdm.asyncio import tqdm
|
| 17 |
+
|
| 18 |
+
# GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
|
| 19 |
+
# ---- ENV VARIABLES ---- #
|
| 20 |
+
"""
|
| 21 |
+
This function will load our environment file (.env) if it is present.
|
| 22 |
+
|
| 23 |
+
NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
|
| 24 |
+
"""
|
| 25 |
+
load_dotenv()
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
We will load our environment variables here.
|
| 29 |
+
"""
|
| 30 |
+
HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
|
| 31 |
+
HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
|
| 32 |
+
HF_TOKEN = os.environ["HF_TOKEN"]
|
| 33 |
+
|
| 34 |
+
# ---- GLOBAL DECLARATIONS ---- #
|
| 35 |
+
|
| 36 |
+
# -- RETRIEVAL -- #
|
| 37 |
+
"""
|
| 38 |
+
1. Load Documents from Text File
|
| 39 |
+
2. Split Documents into Chunks
|
| 40 |
+
3. Load HuggingFace Embeddings (remember to use the URL we set above)
|
| 41 |
+
4. Index Files if they do not exist, otherwise load the vectorstore
|
| 42 |
+
"""
|
| 43 |
+
document_loader = TextLoader("./data/paul_graham_essays.txt")
|
| 44 |
+
documents = document_loader.load()
|
| 45 |
+
|
| 46 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
|
| 47 |
+
split_documents = text_splitter.split_documents(documents)
|
| 48 |
+
|
| 49 |
+
hf_embeddings = HuggingFaceEndpointEmbeddings(
|
| 50 |
+
model=HF_EMBED_ENDPOINT,
|
| 51 |
+
task="feature-extraction",
|
| 52 |
+
huggingfacehub_api_token=HF_TOKEN,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
async def add_documents_async(vectorstore, documents):
|
| 57 |
+
await vectorstore.aadd_documents(documents)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
async def process_batch(vectorstore, batch, is_first_batch, pbar):
|
| 61 |
+
if is_first_batch:
|
| 62 |
+
result = await FAISS.afrom_documents(batch, hf_embeddings)
|
| 63 |
+
else:
|
| 64 |
+
await add_documents_async(vectorstore, batch)
|
| 65 |
+
result = vectorstore
|
| 66 |
+
pbar.update(len(batch))
|
| 67 |
+
return result
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
async def main():
|
| 71 |
+
print("Indexing Files")
|
| 72 |
+
|
| 73 |
+
vectorstore = None
|
| 74 |
+
batch_size = 32
|
| 75 |
+
|
| 76 |
+
batches = [
|
| 77 |
+
split_documents[i : i + batch_size]
|
| 78 |
+
for i in range(0, len(split_documents), batch_size)
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
async def process_all_batches():
|
| 82 |
+
nonlocal vectorstore
|
| 83 |
+
tasks = []
|
| 84 |
+
pbars = []
|
| 85 |
+
|
| 86 |
+
for i, batch in enumerate(batches):
|
| 87 |
+
pbar = tqdm(
|
| 88 |
+
total=len(batch), desc=f"Batch {i + 1}/{len(batches)}", position=i
|
| 89 |
+
)
|
| 90 |
+
pbars.append(pbar)
|
| 91 |
+
|
| 92 |
+
if i == 0:
|
| 93 |
+
vectorstore = await process_batch(None, batch, True, pbar)
|
| 94 |
+
else:
|
| 95 |
+
tasks.append(process_batch(vectorstore, batch, False, pbar))
|
| 96 |
+
|
| 97 |
+
if tasks:
|
| 98 |
+
await asyncio.gather(*tasks)
|
| 99 |
+
|
| 100 |
+
for pbar in pbars:
|
| 101 |
+
pbar.close()
|
| 102 |
+
|
| 103 |
+
await process_all_batches()
|
| 104 |
+
|
| 105 |
+
hf_retriever = vectorstore.as_retriever()
|
| 106 |
+
print("\nIndexing complete. Vectorstore is ready for use.")
|
| 107 |
+
return hf_retriever
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
async def run():
|
| 111 |
+
retriever = await main()
|
| 112 |
+
return retriever
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
hf_retriever = asyncio.run(run())
|
| 116 |
+
|
| 117 |
+
# -- AUGMENTED -- #
|
| 118 |
+
"""
|
| 119 |
+
1. Define a String Template
|
| 120 |
+
2. Create a Prompt Template from the String Template
|
| 121 |
+
"""
|
| 122 |
+
RAG_PROMPT_TEMPLATE = """\
|
| 123 |
+
<|start_header_id|>system<|end_header_id|>
|
| 124 |
+
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|>
|
| 125 |
+
|
| 126 |
+
<|start_header_id|>user<|end_header_id|>
|
| 127 |
+
User Query:
|
| 128 |
+
{query}
|
| 129 |
+
|
| 130 |
+
Context:
|
| 131 |
+
{context}<|eot_id|>
|
| 132 |
+
|
| 133 |
+
<|start_header_id|>assistant<|end_header_id|>
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
|
| 137 |
+
|
| 138 |
+
# -- GENERATION -- #
|
| 139 |
+
"""
|
| 140 |
+
1. Create a HuggingFaceEndpoint for the LLM
|
| 141 |
+
"""
|
| 142 |
+
hf_llm = HuggingFaceEndpoint(
|
| 143 |
+
endpoint_url=HF_LLM_ENDPOINT,
|
| 144 |
+
max_new_tokens=512,
|
| 145 |
+
top_k=10,
|
| 146 |
+
top_p=0.95,
|
| 147 |
+
temperature=0.3,
|
| 148 |
+
repetition_penalty=1.15,
|
| 149 |
+
huggingfacehub_api_token=HF_TOKEN,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@cl.author_rename
|
| 154 |
+
def rename(original_author: str):
|
| 155 |
+
"""
|
| 156 |
+
This function can be used to rename the 'author' of a message.
|
| 157 |
+
|
| 158 |
+
In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
|
| 159 |
+
"""
|
| 160 |
+
rename_dict = {"Assistant": "Paul Graham Essay Bot"}
|
| 161 |
+
return rename_dict.get(original_author, original_author)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@cl.on_chat_start
|
| 165 |
+
async def start_chat():
|
| 166 |
+
"""
|
| 167 |
+
This function will be called at the start of every user session.
|
| 168 |
+
|
| 169 |
+
We will build our LCEL RAG chain here, and store it in the user session.
|
| 170 |
+
|
| 171 |
+
The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
lcel_rag_chain = (
|
| 175 |
+
{"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}
|
| 176 |
+
| rag_prompt
|
| 177 |
+
| hf_llm
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
@cl.on_message
|
| 184 |
+
async def main(message: cl.Message):
|
| 185 |
+
"""
|
| 186 |
+
This function will be called every time a message is recieved from a session.
|
| 187 |
+
|
| 188 |
+
We will use the LCEL RAG chain to generate a response to the user query.
|
| 189 |
+
|
| 190 |
+
The LCEL RAG chain is stored in the user session, and is unique to each user session - this is why we can access it here.
|
| 191 |
+
"""
|
| 192 |
+
lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
|
| 193 |
+
|
| 194 |
+
msg = cl.Message(content="")
|
| 195 |
+
|
| 196 |
+
for chunk in await cl.make_async(lcel_rag_chain.stream)(
|
| 197 |
+
{"query": message.content},
|
| 198 |
+
config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
|
| 199 |
+
):
|
| 200 |
+
await msg.stream_token(chunk)
|
| 201 |
+
|
| 202 |
+
await msg.send()
|
chainlit.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# THIS APP IS A DEMO FOR SHOWING HOW TO USE HUGGING FACE ENDPOINTS
|
data/paul_graham_essays.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pyproject.toml
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[project]
|
| 2 |
+
name = "15-app"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
description = "Session 15 - Open Source Endpoints"
|
| 5 |
+
readme = "README.md"
|
| 6 |
+
requires-python = ">=3.09"
|
| 7 |
+
dependencies = [
|
| 8 |
+
"asyncio===3.4.3",
|
| 9 |
+
"chainlit==2.2.1",
|
| 10 |
+
"huggingface-hub==0.27.0",
|
| 11 |
+
"langchain-huggingface==0.1.2",
|
| 12 |
+
"langchain==0.3.19",
|
| 13 |
+
"langchain-community==0.3.18",
|
| 14 |
+
"langsmith==0.3.11",
|
| 15 |
+
"python-dotenv==1.0.1",
|
| 16 |
+
"tqdm==4.67.1",
|
| 17 |
+
"langchain-openai==0.3.7",
|
| 18 |
+
"langchain-text-splitters==0.3.6",
|
| 19 |
+
"jupyter>=1.1.1",
|
| 20 |
+
"faiss-cpu>=1.10.0",
|
| 21 |
+
"websockets>=15.0",
|
| 22 |
+
]
|
solution_app.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import chainlit as cl
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from operator import itemgetter
|
| 5 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
| 6 |
+
from langchain_community.document_loaders import TextLoader
|
| 7 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 8 |
+
from langchain_community.vectorstores import FAISS
|
| 9 |
+
from langchain_huggingface import HuggingFaceEndpointEmbeddings
|
| 10 |
+
from langchain_core.prompts import PromptTemplate
|
| 11 |
+
from langchain.schema.output_parser import StrOutputParser
|
| 12 |
+
from langchain.schema.runnable import RunnablePassthrough
|
| 13 |
+
from langchain.schema.runnable.config import RunnableConfig
|
| 14 |
+
from tqdm.asyncio import tqdm_asyncio
|
| 15 |
+
import asyncio
|
| 16 |
+
from tqdm.asyncio import tqdm
|
| 17 |
+
|
| 18 |
+
# GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
|
| 19 |
+
# ---- ENV VARIABLES ---- #
|
| 20 |
+
"""
|
| 21 |
+
This function will load our environment file (.env) if it is present.
|
| 22 |
+
|
| 23 |
+
NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
|
| 24 |
+
"""
|
| 25 |
+
load_dotenv()
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
We will load our environment variables here.
|
| 29 |
+
"""
|
| 30 |
+
HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
|
| 31 |
+
HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
|
| 32 |
+
HF_TOKEN = os.environ["HF_TOKEN"]
|
| 33 |
+
|
| 34 |
+
# ---- GLOBAL DECLARATIONS ---- #
|
| 35 |
+
|
| 36 |
+
# -- RETRIEVAL -- #
|
| 37 |
+
"""
|
| 38 |
+
1. Load Documents from Text File
|
| 39 |
+
2. Split Documents into Chunks
|
| 40 |
+
3. Load HuggingFace Embeddings (remember to use the URL we set above)
|
| 41 |
+
4. Index Files if they do not exist, otherwise load the vectorstore
|
| 42 |
+
"""
|
| 43 |
+
document_loader = TextLoader("./data/paul_graham_essays.txt")
|
| 44 |
+
documents = document_loader.load()
|
| 45 |
+
|
| 46 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
|
| 47 |
+
split_documents = text_splitter.split_documents(documents)
|
| 48 |
+
|
| 49 |
+
hf_embeddings = HuggingFaceEndpointEmbeddings(
|
| 50 |
+
model=HF_EMBED_ENDPOINT,
|
| 51 |
+
task="feature-extraction",
|
| 52 |
+
huggingfacehub_api_token=HF_TOKEN,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
async def add_documents_async(vectorstore, documents):
|
| 56 |
+
await vectorstore.aadd_documents(documents)
|
| 57 |
+
|
| 58 |
+
async def process_batch(vectorstore, batch, is_first_batch, pbar):
|
| 59 |
+
if is_first_batch:
|
| 60 |
+
result = await FAISS.afrom_documents(batch, hf_embeddings)
|
| 61 |
+
else:
|
| 62 |
+
await add_documents_async(vectorstore, batch)
|
| 63 |
+
result = vectorstore
|
| 64 |
+
pbar.update(len(batch))
|
| 65 |
+
return result
|
| 66 |
+
|
| 67 |
+
async def main():
|
| 68 |
+
print("Indexing Files")
|
| 69 |
+
|
| 70 |
+
vectorstore = None
|
| 71 |
+
batch_size = 32
|
| 72 |
+
|
| 73 |
+
batches = [split_documents[i:i+batch_size] for i in range(0, len(split_documents), batch_size)]
|
| 74 |
+
|
| 75 |
+
async def process_all_batches():
|
| 76 |
+
nonlocal vectorstore
|
| 77 |
+
tasks = []
|
| 78 |
+
pbars = []
|
| 79 |
+
|
| 80 |
+
for i, batch in enumerate(batches):
|
| 81 |
+
pbar = tqdm(total=len(batch), desc=f"Batch {i+1}/{len(batches)}", position=i)
|
| 82 |
+
pbars.append(pbar)
|
| 83 |
+
|
| 84 |
+
if i == 0:
|
| 85 |
+
vectorstore = await process_batch(None, batch, True, pbar)
|
| 86 |
+
else:
|
| 87 |
+
tasks.append(process_batch(vectorstore, batch, False, pbar))
|
| 88 |
+
|
| 89 |
+
if tasks:
|
| 90 |
+
await asyncio.gather(*tasks)
|
| 91 |
+
|
| 92 |
+
for pbar in pbars:
|
| 93 |
+
pbar.close()
|
| 94 |
+
|
| 95 |
+
await process_all_batches()
|
| 96 |
+
|
| 97 |
+
hf_retriever = vectorstore.as_retriever()
|
| 98 |
+
print("\nIndexing complete. Vectorstore is ready for use.")
|
| 99 |
+
return hf_retriever
|
| 100 |
+
|
| 101 |
+
async def run():
|
| 102 |
+
retriever = await main()
|
| 103 |
+
return retriever
|
| 104 |
+
|
| 105 |
+
hf_retriever = asyncio.run(run())
|
| 106 |
+
|
| 107 |
+
# -- AUGMENTED -- #
|
| 108 |
+
"""
|
| 109 |
+
1. Define a String Template
|
| 110 |
+
2. Create a Prompt Template from the String Template
|
| 111 |
+
"""
|
| 112 |
+
RAG_PROMPT_TEMPLATE = """\
|
| 113 |
+
<|start_header_id|>system<|end_header_id|>
|
| 114 |
+
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|>
|
| 115 |
+
|
| 116 |
+
<|start_header_id|>user<|end_header_id|>
|
| 117 |
+
User Query:
|
| 118 |
+
{query}
|
| 119 |
+
|
| 120 |
+
Context:
|
| 121 |
+
{context}<|eot_id|>
|
| 122 |
+
|
| 123 |
+
<|start_header_id|>assistant<|end_header_id|>
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
|
| 127 |
+
|
| 128 |
+
# -- GENERATION -- #
|
| 129 |
+
"""
|
| 130 |
+
1. Create a HuggingFaceEndpoint for the LLM
|
| 131 |
+
"""
|
| 132 |
+
hf_llm = HuggingFaceEndpoint(
|
| 133 |
+
endpoint_url=HF_LLM_ENDPOINT,
|
| 134 |
+
max_new_tokens=512,
|
| 135 |
+
top_k=10,
|
| 136 |
+
top_p=0.95,
|
| 137 |
+
temperature=0.3,
|
| 138 |
+
repetition_penalty=1.15,
|
| 139 |
+
huggingfacehub_api_token=HF_TOKEN,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
@cl.author_rename
|
| 143 |
+
def rename(original_author: str):
|
| 144 |
+
"""
|
| 145 |
+
This function can be used to rename the 'author' of a message.
|
| 146 |
+
|
| 147 |
+
In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
|
| 148 |
+
"""
|
| 149 |
+
rename_dict = {
|
| 150 |
+
"Assistant" : "Paul Graham Essay Bot"
|
| 151 |
+
}
|
| 152 |
+
return rename_dict.get(original_author, original_author)
|
| 153 |
+
|
| 154 |
+
@cl.on_chat_start
|
| 155 |
+
async def start_chat():
|
| 156 |
+
"""
|
| 157 |
+
This function will be called at the start of every user session.
|
| 158 |
+
|
| 159 |
+
We will build our LCEL RAG chain here, and store it in the user session.
|
| 160 |
+
|
| 161 |
+
The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
lcel_rag_chain = (
|
| 165 |
+
{"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}
|
| 166 |
+
| rag_prompt | hf_llm
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
|
| 170 |
+
|
| 171 |
+
@cl.on_message
|
| 172 |
+
async def main(message: cl.Message):
|
| 173 |
+
"""
|
| 174 |
+
This function will be called every time a message is recieved from a session.
|
| 175 |
+
|
| 176 |
+
We will use the LCEL RAG chain to generate a response to the user query.
|
| 177 |
+
|
| 178 |
+
The LCEL RAG chain is stored in the user session, and is unique to each user session - this is why we can access it here.
|
| 179 |
+
"""
|
| 180 |
+
lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
|
| 181 |
+
|
| 182 |
+
msg = cl.Message(content="")
|
| 183 |
+
|
| 184 |
+
for chunk in await cl.make_async(lcel_rag_chain.stream)(
|
| 185 |
+
{"query": message.content},
|
| 186 |
+
config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
|
| 187 |
+
):
|
| 188 |
+
await msg.stream_token(chunk)
|
| 189 |
+
|
| 190 |
+
await msg.send()
|
uv.lock
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|