achapman commited on
Commit
68c3e9f
·
1 Parent(s): 752236a

use solution app

Browse files
Files changed (3) hide show
  1. app.py +69 -22
  2. chainlit.md +1 -1
  3. requirements.txt +98 -6
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  import chainlit as cl
 
3
  from operator import itemgetter
4
  from langchain_huggingface import HuggingFaceEndpoint
5
  from langchain_community.document_loaders import TextLoader
@@ -7,53 +8,75 @@ from langchain_text_splitters import RecursiveCharacterTextSplitter
7
  from langchain_community.vectorstores import FAISS
8
  from langchain_huggingface import HuggingFaceEndpointEmbeddings
9
  from langchain_core.prompts import PromptTemplate
 
 
10
  from langchain.schema.runnable.config import RunnableConfig
11
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  HF_LLM_ENDPOINT = os.environ["HF_LLM_ENDPOINT"]
13
  HF_EMBED_ENDPOINT = os.environ["HF_EMBED_ENDPOINT"]
14
  HF_TOKEN = os.environ["HF_TOKEN"]
15
 
16
- # -- Data loading, embeddings, vector store --
 
 
 
 
 
 
 
 
17
  document_loader = TextLoader("./data/paul_graham_essays.txt")
18
  documents = document_loader.load()
19
 
20
  text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=30)
21
  split_documents = text_splitter.split_documents(documents)
22
- print("chunked docs")
23
 
24
  hf_embeddings = HuggingFaceEndpointEmbeddings(
25
  model=HF_EMBED_ENDPOINT,
26
  task="feature-extraction",
27
  huggingfacehub_api_token=HF_TOKEN,
28
  )
29
- print("initialized embeddings")
30
-
31
- vectorstore_file = "./data/vectorstore"
32
- vectorstore = None
33
 
34
- if os.path.exists(vectorstore_file):
35
- vectorstore = FAISS.load_local(
36
- vectorstore_file,
37
  hf_embeddings,
38
- allow_dangerous_deserialization=True
39
  )
40
- hf_retriever = vectorstore.as_retriever()
 
41
  else:
 
 
42
  for i in range(0, len(split_documents), 32):
43
- print(f"Embedding batch {i}")
44
  if i == 0:
45
  vectorstore = FAISS.from_documents(split_documents[i:i+32], hf_embeddings)
46
- print("initialized vectorstore")
47
  continue
48
  vectorstore.add_documents(split_documents[i:i+32])
49
- hf_retriever = vectorstore.as_retriever()
50
- print("Created vectorstore")
51
 
52
- ## -- System prompt --
 
 
 
 
 
 
53
  RAG_PROMPT_TEMPLATE = """\
54
  <|start_header_id|>system<|end_header_id|>
55
- You are a helpful expert in tech and entrepreneurship. You answer user questions based on provided context.
56
- If you can't answer the question with the provided context, say you don't know.<|eot_id|>
57
 
58
  <|start_header_id|>user<|end_header_id|>
59
  User Query:
@@ -64,10 +87,13 @@ Context:
64
 
65
  <|start_header_id|>assistant<|end_header_id|>
66
  """
 
67
  rag_prompt = PromptTemplate.from_template(RAG_PROMPT_TEMPLATE)
68
- print("created prompt")
69
 
70
- ## -- LLM endpoint --
 
 
 
71
  hf_llm = HuggingFaceEndpoint(
72
  endpoint_url=HF_LLM_ENDPOINT,
73
  max_new_tokens=512,
@@ -77,10 +103,14 @@ hf_llm = HuggingFaceEndpoint(
77
  repetition_penalty=1.15,
78
  huggingfacehub_api_token=HF_TOKEN,
79
  )
80
- print("initialized endpoint")
81
 
82
  @cl.author_rename
83
  def rename(original_author: str):
 
 
 
 
 
84
  rename_dict = {
85
  "Assistant" : "Paul Graham Essay Bot"
86
  }
@@ -88,17 +118,34 @@ def rename(original_author: str):
88
 
89
  @cl.on_chat_start
90
  async def start_chat():
 
 
 
 
 
 
 
 
91
  lcel_rag_chain = (
92
  {"context": itemgetter("query") | hf_retriever, "query": itemgetter("query")}
93
  | rag_prompt | hf_llm
94
  )
 
95
  cl.user_session.set("lcel_rag_chain", lcel_rag_chain)
96
- await cl.Message(content="I'm ready to chat about tech and entrepreneurship!").send()
97
 
98
  @cl.on_message
99
  async def main(message: cl.Message):
 
 
 
 
 
 
 
100
  lcel_rag_chain = cl.user_session.get("lcel_rag_chain")
 
101
  msg = cl.Message(content="")
 
102
  for chunk in await cl.make_async(lcel_rag_chain.stream)(
103
  {"query": message.content},
104
  config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
 
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
 
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:
 
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,
 
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
  }
 
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()]),
chainlit.md CHANGED
@@ -1 +1 @@
1
- This RAG app uses HuggingFace-hosted enpoints for its embeddings (Snowflake Arctic) and its LLM (Llama 3.1 8B). It uses Paul Graham's essays to discuss entrepreneurship and tech.
 
1
+ # FILL OUT YOUR CHAINLIT MD HERE WITH A DESCRIPTION OF YOUR APPLICATION
requirements.txt CHANGED
@@ -1,8 +1,100 @@
1
- chainlit==1.1.302
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ aiohappyeyeballs==2.4.3
3
+ aiohttp==3.10.8
4
+ aiosignal==1.3.1
5
+ annotated-types==0.7.0
6
+ anyio==3.7.1
7
+ async-timeout==4.0.3
8
+ asyncer==0.0.2
9
+ attrs==24.2.0
10
+ bidict==0.23.1
11
+ certifi==2024.8.30
12
+ chainlit==0.7.700
13
+ charset-normalizer==3.3.2
14
+ click==8.1.7
15
+ dataclasses-json==0.5.14
16
  langchain_huggingface==0.0.3
17
+ Deprecated==1.2.14
18
+ distro==1.9.0
19
+ exceptiongroup==1.2.2
20
+ fastapi==0.100.1
21
+ fastapi-socketio==0.0.10
22
+ filetype==1.2.0
23
+ frozenlist==1.4.1
24
+ googleapis-common-protos==1.65.0
25
+ greenlet==3.1.1
26
+ grpcio==1.66.2
27
+ grpcio-tools==1.62.3
28
+ h11==0.14.0
29
+ h2==4.1.0
30
+ hpack==4.0.0
31
+ httpcore==0.17.3
32
+ httpx==0.24.1
33
+ hyperframe==6.0.1
34
+ idna==3.10
35
+ importlib_metadata==8.4.0
36
+ jiter==0.5.0
37
+ jsonpatch==1.33
38
+ jsonpointer==3.0.0
39
+ langchain==0.3.0
40
+ langchain-community==0.3.0
41
+ langchain-core==0.3.1
42
+ langchain-openai==0.2.0
43
+ langchain-qdrant==0.1.4
44
+ langchain-text-splitters==0.3.0
45
+ langsmith==0.1.121
46
+ Lazify==0.4.0
47
+ marshmallow==3.22.0
48
+ multidict==6.1.0
49
+ mypy-extensions==1.0.0
50
+ nest-asyncio==1.6.0
51
+ numpy==1.26.4
52
+ openai==1.51.0
53
+ opentelemetry-api==1.27.0
54
+ opentelemetry-exporter-otlp==1.27.0
55
+ opentelemetry-exporter-otlp-proto-common==1.27.0
56
+ opentelemetry-exporter-otlp-proto-grpc==1.27.0
57
+ opentelemetry-exporter-otlp-proto-http==1.27.0
58
+ opentelemetry-instrumentation==0.48b0
59
+ opentelemetry-proto==1.27.0
60
+ opentelemetry-sdk==1.27.0
61
+ opentelemetry-semantic-conventions==0.48b0
62
+ orjson==3.10.7
63
+ packaging==23.2
64
+ portalocker==2.10.1
65
+ protobuf==4.25.5
66
+ pydantic==2.9.2
67
+ pydantic-settings==2.5.2
68
+ pydantic_core==2.23.4
69
+ PyJWT==2.9.0
70
+ PyMuPDF==1.24.10
71
+ PyMuPDFb==1.24.10
72
  python-dotenv==1.0.1
73
+ python-engineio==4.9.1
74
+ python-graphql-client==0.4.3
75
+ python-multipart==0.0.6
76
+ python-socketio==5.11.4
77
+ PyYAML==6.0.2
78
+ qdrant-client==1.11.2
79
+ regex==2024.9.11
80
+ requests==2.32.3
81
+ simple-websocket==1.0.0
82
+ sniffio==1.3.1
83
+ SQLAlchemy==2.0.35
84
+ starlette==0.27.0
85
+ syncer==2.0.3
86
+ tenacity==8.5.0
87
+ tiktoken==0.7.0
88
+ tomli==2.0.1
89
+ tqdm==4.66.5
90
+ typing-inspect==0.9.0
91
+ typing_extensions==4.12.2
92
+ uptrace==1.26.0
93
+ urllib3==2.2.3
94
+ uvicorn==0.23.2
95
+ watchfiles==0.20.0
96
+ websockets==13.1
97
+ wrapt==1.16.0
98
+ wsproto==1.2.0
99
+ yarl==1.13.1
100
+ zipp==3.20.2