Sanjeev Lakkaraju commited on
Commit
9708f2a
·
1 Parent(s): fb69c6d

add the changes to app.py

Browse files
Files changed (9) hide show
  1. .env.sample +5 -0
  2. .gitignore +6 -0
  3. Dockerfile +11 -0
  4. README (2).md +150 -0
  5. app.py +163 -0
  6. chainlit.md +1 -0
  7. data/paul_graham_essays.txt +0 -0
  8. requirements.txt +8 -0
  9. solution_app.py +155 -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
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+ RUN useradd -m -u 1000 user
3
+ USER user
4
+ ENV HOME=/home/user \
5
+ PATH=/home/user/.local/bin:$PATH
6
+ WORKDIR $HOME/app
7
+ COPY --chown=user . $HOME/app
8
+ COPY ./requirements.txt ~/app/requirements.txt
9
+ RUN pip install -r requirements.txt
10
+ COPY . .
11
+ CMD ["chainlit", "run", "app.py", "--port", "7860"]
README (2).md ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Week 4: Tuesday
2
+
3
+ In today's assignment, we'll be creating an Open Source LLM-powered LangChain RAG Application in Chainlit.
4
+
5
+ There are 2 main sections to this assignment:
6
+
7
+ ## Build 🏗️
8
+
9
+ ### Build Task 1: Deploy LLM and Embedding Model to SageMaker Endpoint Through Hugging Face Inference Endpoints
10
+
11
+ #### LLM Endpoint
12
+
13
+ Select "Inference Endpoint" from the "Solutions" button in Hugging Face:
14
+
15
+ ![image](https://i.imgur.com/6KC9TCD.png)
16
+
17
+ Create a "+ New Endpoint" from the Inference Endpoints dashboard.
18
+
19
+ ![image](https://i.imgur.com/G6Bq9KC.png)
20
+
21
+ Select the `NousResearch/Meta-Llama-3-8B-Instruct` model repository and name your endpoint. Select N. Virginia as your region (`us-east-1`). Give your endpoint an appropriate name. Make sure to select *at least* a L4 GPU.
22
+
23
+ ![image](https://i.imgur.com/X3YlUbh.png)
24
+
25
+ Select the following settings for your `Advanced Configuration`.
26
+
27
+ ![image](https://i.imgur.com/c0HQ7g1.png)
28
+
29
+ Create a `Protected` endpoint.
30
+
31
+ ![image](https://i.imgur.com/Ak8kchZ.png)
32
+
33
+ If you were successful, you should see the following screen:
34
+
35
+ ![image](https://i.imgur.com/IBYG3wm.png)
36
+
37
+ #### Embedding Model Endpoint
38
+ We'll be using `Snowflake/snowflake-arctic-embed-m` for our embedding model today.
39
+
40
+ The process is the same as the LLM - but we'll make a few specific tweaks:
41
+
42
+ Let's make sure our set-up reflects the following screenshots:
43
+
44
+ ![image](https://i.imgur.com/IHh8FnC.png)
45
+
46
+ After which, make sure the advanced configuration is set like so:
47
+
48
+ ![image](https://i.imgur.com/bbcrhUj.png)
49
+
50
+ > #### NOTE: PLEASE SHUTDOWN YOUR INSTANCES WHEN YOU HAVE COMPLETED THE ASSIGNMENT TO PREVENT UNESSECARY CHARGES.
51
+
52
+ ### Build Task 2: Create RAG Pipeline with LangChain
53
+
54
+ Follow the [notebook](https://colab.research.google.com/drive/1v1FYmvKH4gsqcdZwIT9wvbQe0GUjrc9d?usp=sharing) to create a LangChain pipeline powered by Hugging Face endpoints!
55
+
56
+ Once you're done - please move on to Build Task 3!
57
+
58
+ ### Build Task 3: Create a Chainlit Application
59
+
60
+ 1. Create a new empty Docker space through Hugging Face - with the following settings:
61
+
62
+ ![image](https://i.imgur.com/0YzyQX7.png)
63
+
64
+ > NOTE: You may notice the application builds slowly (~15min.) with the default free-tier hardware. The process will be faster using the `CPU upgrade` Space Hardware - though it is not required.
65
+
66
+ 2. Clone the newly created space into a directory that is *NOT IN YOUR AI MAKERSPACE REPOSITORY* using the SSH option.
67
+
68
+ > NOTE: You may need to ensure you've added your SSH key to Hugging Face, as well as GitHub. This should already be done.
69
+
70
+ ![image](https://i.imgur.com/5RyBdP5.png)
71
+
72
+ 3. Copy and Paste (`cp ...` or through UI) the contents of `Week 4/Day 1` into the newly cloned repository.
73
+
74
+ > NOTE: Please keep the `README.md` that was cloned from your space and delete the class `README.md`.
75
+
76
+ 4. Using the `ls` command or the `tree` command verify that you have copied over:
77
+ - `app.py`
78
+ - `Dockerfile`
79
+ - `data/paul_graham_essays.txt`
80
+ - `chainlit.md`
81
+ - `.gitignore`
82
+ - `.env.sample`
83
+ - `solution_app.py`
84
+ - `requirements.txt`
85
+
86
+ Here is an example as the `ls -al` CLI command:
87
+
88
+ ![image](https://i.imgur.com/vazGYeb.png)
89
+
90
+ 5. Work through the `app.py` file to migrate your LCEL LangChain RAG Chain from the Notebook to Chainlit!
91
+
92
+ 6. Be sure to modify your `README.md` and `chainlit.md` as you see fit!
93
+
94
+ > NOTE: If you get stuck, there is a working reference version in `solution_app.py`.
95
+
96
+ 7. When you are done with local testing - push your changes to your space.
97
+
98
+ 8. Make sure you add your `HF_LLM_ENDPOINT`, `HF_EMBED_ENDPOINT`, `HF_TOKEN` as "Secrets" in your Hugging Face Space.
99
+
100
+ ### Terminating Your Resources
101
+
102
+ Please head to the settings of each endpoint and select `Delete Endpoint`. You will need to type the name of the endpoint to delete the resources.
103
+
104
+ ### Deliverables
105
+
106
+ - Completed Notebook
107
+ - Chainlit Application in a Hugging Face Space Powered by Hugging Face Endpoints
108
+ - Screenshot of endpoint usage
109
+
110
+ Example Screen Shot:
111
+
112
+ ![image](https://i.imgur.com/qfbcVpS.png)
113
+
114
+ ## Ship 🚢
115
+
116
+ Create a Hugging Face Space powered by Hugging Face Endpoints!
117
+
118
+ ### Deliverables
119
+
120
+ - A short Loom of the space, and a 1min. walkthrough of the application in full
121
+
122
+ ## Share 🚀
123
+
124
+ Make a social media post about your final application!
125
+
126
+ ### Deliverables
127
+
128
+ - Make a post on any social media platform about what you built!
129
+
130
+ Here's a template to get you started:
131
+
132
+ ```
133
+ 🚀 Exciting News! 🚀
134
+
135
+ I am thrilled to announce that I have just built and shipped a open-source LLM-powered Retrieval Augmented Generation Application with LangChain! 🎉🤖
136
+
137
+ 🔍 Three Key Takeaways:
138
+ 1️⃣
139
+ 2️⃣
140
+ 3️⃣
141
+
142
+ Let's continue pushing the boundaries of what's possible in the world of AI and question-answering. Here's to many more innovations! 🚀
143
+ Shout out to @AIMakerspace !
144
+
145
+ #LangChain #QuestionAnswering #RetrievalAugmented #Innovation #AI #TechMilestone
146
+
147
+ Feel free to reach out if you're curious or would like to collaborate on similar projects! 🤝🔥
148
+ ```
149
+
150
+ > #### NOTE: PLEASE SHUTDOWN YOUR INSTANCES WHEN YOU HAVE COMPLETED THE ASSIGNMENT TO PREVENT UNESSECARY CHARGES.
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ # GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
16
+ # ---- ENV VARIABLES ---- #
17
+ """
18
+ This function will load our environment file (.env) if it is present.
19
+
20
+ NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
21
+ """
22
+ load_dotenv()
23
+
24
+ """
25
+ We will load our environment variables here.
26
+ """
27
+ HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
28
+ HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
29
+ HF_TOKEN = os.environ["HF_TOKEN"]
30
+
31
+ # ---- GLOBAL DECLARATIONS ---- #
32
+
33
+ # -- RETRIEVAL -- #
34
+ """
35
+ 1. Load Documents from Text File
36
+ 2. Split Documents into Chunks
37
+ 3. Load HuggingFace Embeddings (remember to use the URL we set above)
38
+ 4. Index Files if they do not exist, otherwise load the vectorstore
39
+ """
40
+ ### 1. CREATE TEXT LOADER AND LOAD DOCUMENTS
41
+ ### NOTE: PAY ATTENTION TO THE PATH THEY ARE IN.
42
+ text_loader = TextLoader("data/paul_graham_essays.txt")
43
+ documents = text_loader.load()
44
+
45
+ ### 2. CREATE TEXT SPLITTER AND SPLIT DOCUMENTS
46
+ text_splitter = RecursiveCharacterTextSplitter(
47
+ chunk_size=1000,
48
+ chunk_overlap=30,
49
+ length_function=len,
50
+ is_separator_regex=False,
51
+ )
52
+ split_documents = text_splitter.split_documents(documents)
53
+
54
+ ### 3. LOAD HUGGINGFACE EMBEDDINGS
55
+ hf_embeddings = HuggingFaceEndpointEmbeddings(
56
+ model=HF_EMBED_ENDPOINT,
57
+ task="feature-extraction",
58
+ huggingfacehub_api_token=HF_TOKEN,
59
+ )
60
+
61
+ if os.path.exists("./data/vectorstore"):
62
+ vectorstore = FAISS.load_local(
63
+ "./data/vectorstore",
64
+ hf_embeddings,
65
+ allow_dangerous_deserialization=True # this is necessary to load the vectorstore from disk as it's stored as a `.pkl` file.
66
+ )
67
+ hf_retriever = vectorstore.as_retriever()
68
+ print("Loaded Vectorstore")
69
+ else:
70
+ print("Indexing Files")
71
+ os.makedirs("./data/vectorstore", exist_ok=True)
72
+
73
+ ### 4. INDEX FILES
74
+ ### NOTE: REMEMBER TO BATCH THE DOCUMENTS WITH MAXIMUM BATCH SIZE = 32
75
+
76
+ hf_retriever = vectorstore.as_retriever()
77
+
78
+ # -- AUGMENTED -- #
79
+ """
80
+ 1. Define a String Template
81
+ 2. Create a Prompt Template from the String Template
82
+ """
83
+ ### 1. DEFINE STRING TEMPLATE
84
+ RAG_PROMPT_TEMPLATE = """\
85
+ <|start_header_id|>system<|end_header_id|>
86
+ 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|>
87
+
88
+ <|start_header_id|>user<|end_header_id|>
89
+ User Query:
90
+ {query}
91
+
92
+ Context:
93
+ {context}<|eot_id|>
94
+
95
+ <|start_header_id|>assistant<|end_header_id|>
96
+ """
97
+
98
+ ### 2. CREATE PROMPT TEMPLATE
99
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
100
+
101
+ # -- GENERATION -- #
102
+ """
103
+ 1. Create a HuggingFaceEndpoint for the LLM
104
+ """
105
+ ### 1. CREATE HUGGINGFACE ENDPOINT FOR LLM
106
+ hf_llm = HuggingFaceEndpoint(
107
+ endpoint_url=HF_LLM_ENDPOINT,
108
+ max_new_tokens=512,
109
+ top_k=10,
110
+ top_p=0.95,
111
+ typical_p=0.95,
112
+ temperature=0.01,
113
+ repetition_penalty=1.03,
114
+ huggingfacehub_api_token=os.environ["HF_TOKEN"]
115
+ )
116
+
117
+ @cl.author_rename
118
+ def rename(original_author: str):
119
+ """
120
+ This function can be used to rename the 'author' of a message.
121
+
122
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
123
+ """
124
+ rename_dict = {
125
+ "Assistant" : "Paul Graham Essay Bot"
126
+ }
127
+ return rename_dict.get(original_author, original_author)
128
+
129
+ @cl.on_chat_start
130
+ async def start_chat():
131
+ """
132
+ This function will be called at the start of every user session.
133
+
134
+ We will build our LCEL RAG chain here, and store it in the user session.
135
+
136
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
137
+ """
138
+
139
+ ### BUILD LCEL RAG CHAIN THAT ONLY RETURNS TEXT
140
+ lcel_rag_chain = {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}| rag_prompt | hf_llm
141
+
142
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
143
+
144
+ @cl.on_message
145
+ async def main(message: cl.Message):
146
+ """
147
+ This function will be called every time a message is recieved from a session.
148
+
149
+ We will use the LCEL RAG chain to generate a response to the user query.
150
+
151
+ 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.
152
+ """
153
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
154
+
155
+ msg = cl.Message(content="")
156
+
157
+ async for chunk in lcel_rag_chain.astream(
158
+ {"query": message.content},
159
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
160
+ ):
161
+ await msg.stream_token(chunk)
162
+
163
+ await msg.send()
chainlit.md ADDED
@@ -0,0 +1 @@
 
 
1
+ # This is Stock-Analyzer App in Beta
data/paul_graham_essays.txt ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ chainlit==0.7.700
2
+ langchain==0.2.5
3
+ langchain_community==0.2.5
4
+ langchain_core==0.2.9
5
+ langchain_huggingface==0.0.3
6
+ langchain_text_splitters==0.2.1
7
+ python-dotenv==1.0.1
8
+ faiss-cpu
solution_app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ # GLOBAL SCOPE - ENTIRE APPLICATION HAS ACCESS TO VALUES SET IN THIS SCOPE #
16
+ # ---- ENV VARIABLES ---- #
17
+ """
18
+ This function will load our environment file (.env) if it is present.
19
+
20
+ NOTE: Make sure that .env is in your .gitignore file - it is by default, but please ensure it remains there.
21
+ """
22
+ load_dotenv()
23
+
24
+ """
25
+ We will load our environment variables here.
26
+ """
27
+ HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
28
+ HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
29
+ HF_TOKEN = os.environ["HF_TOKEN"]
30
+
31
+ # ---- GLOBAL DECLARATIONS ---- #
32
+
33
+ # -- RETRIEVAL -- #
34
+ """
35
+ 1. Load Documents from Text File
36
+ 2. Split Documents into Chunks
37
+ 3. Load HuggingFace Embeddings (remember to use the URL we set above)
38
+ 4. Index Files if they do not exist, otherwise load the vectorstore
39
+ """
40
+ document_loader = TextLoader("./data/paul_graham_essays.txt")
41
+ documents = document_loader.load()
42
+
43
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
44
+ split_documents = text_splitter.split_documents(documents)
45
+
46
+ hf_embeddings = HuggingFaceEndpointEmbeddings(
47
+ model=HF_EMBED_ENDPOINT,
48
+ task="feature-extraction",
49
+ huggingfacehub_api_token=HF_TOKEN,
50
+ )
51
+
52
+ if os.path.exists("./data/vectorstore"):
53
+ vectorstore = FAISS.load_local(
54
+ "./data/vectorstore",
55
+ hf_embeddings,
56
+ allow_dangerous_deserialization=True # this is necessary to load the vectorstore from disk as it's stored as a `.pkl` file.
57
+ )
58
+ hf_retriever = vectorstore.as_retriever()
59
+ print("Loaded Vectorstore")
60
+ else:
61
+ print("Indexing Files")
62
+ os.makedirs("./data/vectorstore", exist_ok=True)
63
+ for i in range(0, len(split_documents), 32):
64
+ if i == 0:
65
+ vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)
66
+ continue
67
+ vectorstore.add_documents(split_documents[i:i+32])
68
+ vectorstore.save_local("./data/vectorstore")
69
+
70
+ hf_retriever = vectorstore.as_retriever()
71
+
72
+ # -- AUGMENTED -- #
73
+ """
74
+ 1. Define a String Template
75
+ 2. Create a Prompt Template from the String Template
76
+ """
77
+ RAG_PROMPT_TEMPLATE = """\
78
+ <|start_header_id|>system<|end_header_id|>
79
+ 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|>
80
+
81
+ <|start_header_id|>user<|end_header_id|>
82
+ User Query:
83
+ {query}
84
+
85
+ Context:
86
+ {context}<|eot_id|>
87
+
88
+ <|start_header_id|>assistant<|end_header_id|>
89
+ """
90
+
91
+ rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
92
+
93
+ # -- GENERATION -- #
94
+ """
95
+ 1. Create a HuggingFaceEndpoint for the LLM
96
+ """
97
+ hf_llm = HuggingFaceEndpoint(
98
+ endpoint_url=HF_LLM_ENDPOINT,
99
+ max_new_tokens=512,
100
+ top_k=10,
101
+ top_p=0.95,
102
+ temperature=0.3,
103
+ repetition_penalty=1.15,
104
+ huggingfacehub_api_token=HF_TOKEN,
105
+ )
106
+
107
+ @cl.author_rename
108
+ def rename(original_author: str):
109
+ """
110
+ This function can be used to rename the 'author' of a message.
111
+
112
+ In this case, we're overriding the 'Assistant' author to be 'Paul Graham Essay Bot'.
113
+ """
114
+ rename_dict = {
115
+ "Assistant" : "Paul Graham Essay Bot"
116
+ }
117
+ return rename_dict.get(original_author, original_author)
118
+
119
+ @cl.on_chat_start
120
+ async def start_chat():
121
+ """
122
+ This function will be called at the start of every user session.
123
+
124
+ We will build our LCEL RAG chain here, and store it in the user session.
125
+
126
+ The user session is a dictionary that is unique to each user session, and is stored in the memory of the server.
127
+ """
128
+
129
+ lcel_rag_chain = (
130
+ {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}
131
+ | rag_prompt | hf_llm
132
+ )
133
+
134
+ cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
135
+
136
+ @cl.on_message
137
+ async def main(message: cl.Message):
138
+ """
139
+ This function will be called every time a message is recieved from a session.
140
+
141
+ We will use the LCEL RAG chain to generate a response to the user query.
142
+
143
+ 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.
144
+ """
145
+ lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
146
+
147
+ msg = cl.Message(content="")
148
+
149
+ for chunk in await cl.make_async(lcel_rag_chain.stream)(
150
+ {"query": message.content},
151
+ config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
152
+ ):
153
+ await msg.stream_token(chunk)
154
+
155
+ await msg.send()