Spaces:
Sleeping
Sleeping
init
Browse files- My_Notion_Companion.py +88 -0
- pages/2_Technical_Implementation.py +156 -0
- pages/3_Motivation.py +34 -0
My_Notion_Companion.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Entry point to Streamlit UI.
|
2 |
+
|
3 |
+
Ref: https://docs.streamlit.io/get-started/tutorials/create-a-multipage-app
|
4 |
+
"""
|
5 |
+
|
6 |
+
from pathlib import Path
|
7 |
+
from typing import Dict
|
8 |
+
|
9 |
+
import streamlit as st
|
10 |
+
|
11 |
+
|
12 |
+
def welcome_message() -> Dict[str, str]:
|
13 |
+
return {
|
14 |
+
"role": "assistant",
|
15 |
+
"content": "Welcome to My Notion Companion.",
|
16 |
+
}
|
17 |
+
|
18 |
+
|
19 |
+
def main():
|
20 |
+
|
21 |
+
st.set_page_config(
|
22 |
+
page_title="My Notion Companion",
|
23 |
+
page_icon="🤖",
|
24 |
+
)
|
25 |
+
|
26 |
+
st.title("My Notion Companion 🤖")
|
27 |
+
st.caption(
|
28 |
+
"A conversational RAG that helps to chat with my (mostly Chinese-based) Notion Databases."
|
29 |
+
)
|
30 |
+
st.caption(
|
31 |
+
"Powered by: [🦜🔗](https://www.langchain.com/), [🤗](https://huggingface.co/), [LlamaCpp](https://github.com/ggerganov/llama.cpp), [Streamlit](https://streamlit.io/)."
|
32 |
+
)
|
33 |
+
|
34 |
+
# Initialize chat history
|
35 |
+
if "messages" not in st.session_state:
|
36 |
+
st.session_state.messages = [welcome_message()]
|
37 |
+
|
38 |
+
# Display chat messages from history on app rerun
|
39 |
+
for message in st.session_state.messages:
|
40 |
+
with st.chat_message(message["role"]):
|
41 |
+
st.markdown(message["content"])
|
42 |
+
|
43 |
+
# Two buttons to control history/memory
|
44 |
+
def start_over():
|
45 |
+
st.session_state.messages = [
|
46 |
+
{"role": "assistant", "content": "Okay, let's start over."}
|
47 |
+
]
|
48 |
+
|
49 |
+
st.sidebar.button(
|
50 |
+
"Start All Over Again", on_click=start_over, use_container_width=True
|
51 |
+
)
|
52 |
+
|
53 |
+
def clear_chat_history():
|
54 |
+
st.session_state.messages = [
|
55 |
+
{
|
56 |
+
"role": "assistant",
|
57 |
+
"content": "Retrieved documents are still in my memory. What else you want to know?",
|
58 |
+
}
|
59 |
+
]
|
60 |
+
|
61 |
+
st.sidebar.button(
|
62 |
+
"Keep Retrieved Docs but Clear Chat History",
|
63 |
+
on_click=clear_chat_history,
|
64 |
+
use_container_width=True,
|
65 |
+
)
|
66 |
+
|
67 |
+
# Accept user input
|
68 |
+
if prompt := st.chat_input("Any questiones?"):
|
69 |
+
|
70 |
+
# Add user message to chat history
|
71 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
72 |
+
|
73 |
+
# Display user message in chat message container
|
74 |
+
with st.chat_message("user"):
|
75 |
+
st.markdown(prompt)
|
76 |
+
|
77 |
+
# Display assistant response in chat message container
|
78 |
+
with st.chat_message("assistant"):
|
79 |
+
# response = st.session_state.t.invoke()
|
80 |
+
response = """##### NOTES: \n\nThis is only a mock UI hosted on Hugging Face because of limited computing resources available as a freemium user.
|
81 |
+
Please check the video demo (side bar) and see how this the companion works as a standalone offline webapp.\n\nAlternatively,
|
82 |
+
please visit the [GitHub page](https://github.com/fyang0507/my-notion-companion/tree/main) and follow the quickstart guide to build your own!
|
83 |
+
"""
|
84 |
+
st.write(response)
|
85 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
86 |
+
|
87 |
+
if __name__ == "__main__":
|
88 |
+
main()
|
pages/2_Technical_Implementation.py
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import streamlit as st
|
3 |
+
|
4 |
+
st.set_page_config(
|
5 |
+
page_title="Implementation",
|
6 |
+
page_icon="⚙️",
|
7 |
+
)
|
8 |
+
st.markdown("## What's under the hood? ⚙️")
|
9 |
+
|
10 |
+
st.markdown(
|
11 |
+
"""
|
12 |
+
My Notion Companion is a LLM-powered conversational RAG to chat with documents from Notion.
|
13 |
+
It uses hybrid search (lexical + semantic) search to find the relevant documents and a chat interface to interact with the docs.
|
14 |
+
It uses only **open-sourced technologies** and can **run on a single Mac Mini**.
|
15 |
+
|
16 |
+
Empowering technologies:
|
17 |
+
- **The Framework**: uses [Langchain](https://python.langchain.com/docs/)
|
18 |
+
- **The LLM**: uses 🤗-developed [`HuggingFaceH4/zephyr-7b-beta`](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta). It has great inference speed, bilingual and instruction following capabilities
|
19 |
+
- **The Datastores**: the documents were stored into both conventional lexical data form and embeeding-based vectorstore (uses [Redis](https://python.langchain.com/docs/integrations/vectorstores/redis))
|
20 |
+
- **The Embedding Model**: uses [`sentence-transformers/distiluse-base-multilingual-cased-v1`](https://huggingface.co/sentence-transformers/distiluse-base-multilingual-cased-v1). It has great inference speed and bilingual capability
|
21 |
+
- **The Tokenizers**: uses 🤗's [`AutoTokenizer`](AutoTokenizer) and Chinese text segmentation tool [`jieba`](https://github.com/fxsjy/jieba) (only in lexical search)
|
22 |
+
- **The Lexical Search Tool**: uses [`rank_bm25`](https://github.com/dorianbrown/rank_bm25)
|
23 |
+
- **The Computing**: uses [LlamaCpp](https://github.com/ggerganov/llama.cpp) to power the LLM in the local machine (a Mac Mini with M2 Pro chip)
|
24 |
+
- **The Observability Tool**: uses [LangSmith](https://docs.smith.langchain.com/)
|
25 |
+
- **The UI**: uses [Streamlit](https://docs.streamlit.io/)
|
26 |
+
"""
|
27 |
+
)
|
28 |
+
|
29 |
+
|
30 |
+
st.markdown(
|
31 |
+
"""
|
32 |
+
#### The E2E Pipeline
|
33 |
+
|
34 |
+
- When a user enters a prompt, the assistant will try lexical search first
|
35 |
+
- a query analyzer will analyze the query and extract keywords (for search) and domains (for metadata filtering)
|
36 |
+
- the extracted domains will be compared against the metadata of documents, only those with a matched metadata will be retrieved
|
37 |
+
- the keyword will be segmented into searchable tokens, then further compared against the metadata-filtered documents with BM25 lexical search algorithm
|
38 |
+
- The fetched documents will be subject to a final match checker to ensure relevance
|
39 |
+
- If lexical search doesn't return enough documents, the assistant will then try semantic search into the Redis vectorstore. Retrieved docs will also subject the QA by match checker.
|
40 |
+
- All retrieved documents will be sent to LLM as part of a system prompt, the LLM will then act as a conversational RAG to chat with the user with knowledges from the provided documents
|
41 |
+
|
42 |
+
"""
|
43 |
+
)
|
44 |
+
|
45 |
+
st.image("resources/flowchart.png", caption="E2E workflow")
|
46 |
+
|
47 |
+
|
48 |
+
st.markdown(
|
49 |
+
"""
|
50 |
+
#### Selecting the right LLM
|
51 |
+
|
52 |
+
I have compared a wide range of Bi/Multi-lingual LLMs with 7B parameters that has a LlamaCpp-friendly gguf executable on HuggingFace (which can fit onto Mac Mini's GPU).
|
53 |
+
|
54 |
+
I created conversational test cases to assess the models' instruction following, reasoning, helpfulness, coding, hallucinations and inference speed.
|
55 |
+
Qwen models (Qwen 1.0 & 1.5), together with HuggingFace's zephyr-7b-beta come as the top 3, but Qwen models are overly creative and do not follow few-shot examples.
|
56 |
+
Thus, the final candidate goes to **zephyr**.
|
57 |
+
|
58 |
+
Access the complete LLM evaluation results [here](https://docs.google.com/spreadsheets/d/1OZKu6m0fHPYkbf9SBV6UUOE_flgBG7gphgyo2rzOpsU/edit?usp=sharing).
|
59 |
+
"""
|
60 |
+
)
|
61 |
+
|
62 |
+
df_llm = pd.read_csv("resources/llm_scores.csv", index_col=0)
|
63 |
+
|
64 |
+
st.dataframe(df_llm)
|
65 |
+
|
66 |
+
st.markdown(
|
67 |
+
"""
|
68 |
+
#### Selecting the right LLM Computing Platform
|
69 |
+
|
70 |
+
I tested [Ollama](https://ollama.com/) first given its integrated, worry-free experiences that abstracted away the complexity of building environments and downloading LLMs.
|
71 |
+
However, I hit some unresponsiveness when experimenting with different LLMs and switched to [LlamaCpp](https://github.com/ggerganov/llama.cpp) (one layer deeper as the empowering backend for Ollama)
|
72 |
+
|
73 |
+
It works great so I sticked around.
|
74 |
+
"""
|
75 |
+
)
|
76 |
+
|
77 |
+
st.markdown(
|
78 |
+
"""
|
79 |
+
#### Selecting the right Vectordatabase
|
80 |
+
|
81 |
+
Langchain supports a huge number of vectordatabases. Because I don't have any scalability concerns (<300 docs in total),
|
82 |
+
I target on easiness, can run in local machine, supports to offload data into disk, and metadata fuzzy match.
|
83 |
+
|
84 |
+
Redis ended up being the only option that satisfies all the criteria.
|
85 |
+
"""
|
86 |
+
)
|
87 |
+
|
88 |
+
df_vs = pd.read_csv("resources/vectordatabase_evaluation.csv", index_col=0)
|
89 |
+
|
90 |
+
st.dataframe(df_vs)
|
91 |
+
|
92 |
+
st.markdown(
|
93 |
+
"""
|
94 |
+
#### Selecting the right Embedding Model
|
95 |
+
|
96 |
+
Many companies have released their embeddings models. Our search begins with bi/multi-lingual embedding models
|
97 |
+
developed by top-tier tech companies and research labs, with sizes from 500MB-2.2GB.
|
98 |
+
|
99 |
+
Our evaluation dataset contains hand-crafted question-document pairs. Where the document contains the information to answer the associated question.
|
100 |
+
Similar to [**CLIP**](https://openai.com/research/clip) method, I uses a "contrastive loss function" to evaluate the model such that we maximize the differences between paired and unpaired question-doc pairs.
|
101 |
+
|
102 |
+
```
|
103 |
+
loss = np.abs(
|
104 |
+
cos_sim(embedding(q), embedding(doc_paired)) -
|
105 |
+
np.mean(cos_sim(embedding(q), embedding(doc_unpaired)))
|
106 |
+
)
|
107 |
+
```
|
108 |
+
|
109 |
+
In addition, I also considers model size and loading/inference speed for each model.
|
110 |
+
|
111 |
+
`sentence-transformers/distiluse-base-multilingual-cased-v1` turns out to be the best candidate with the top-class inference speed and best contrastive loss.
|
112 |
+
|
113 |
+
Check the evaluation notebook [here](https://github.com/fyang0507/my-notion-companion/blob/main/playground/evaluate_embedding_models.ipynb).
|
114 |
+
"""
|
115 |
+
)
|
116 |
+
|
117 |
+
df_embedding = pd.read_csv("resources/embedding_model_scores.csv", index_col=0)
|
118 |
+
|
119 |
+
st.dataframe(df_embedding)
|
120 |
+
|
121 |
+
|
122 |
+
st.markdown(
|
123 |
+
"""
|
124 |
+
#### Selecting the right Observability Tool
|
125 |
+
|
126 |
+
Langchain ecosystem comes with its own [LangSmith](https://www.langchain.com/langsmith) observability tool. It works out of the box with minimal added configurations and requires no change in codes.
|
127 |
+
|
128 |
+
LLM responses are somtimes unpredictable (especially a small 7B model, with multilingual capability), and it only gets more complex as we build the application as a LLM-chain.
|
129 |
+
Below is a single observability trace recorded in LangSmith with a single query "谁曾在步行者队效力?从“写作”中找答案。" (Who plays in Indiana Pacers? Find the answer from Articles.)
|
130 |
+
|
131 |
+
LangSmith helps organize the LLM calls and captures the I/O along the process, making the head-scratching debugging process much less misearble.
|
132 |
+
"""
|
133 |
+
)
|
134 |
+
|
135 |
+
st.video("resources/langsmith_walkthrough.mp4")
|
136 |
+
|
137 |
+
|
138 |
+
st.markdown(
|
139 |
+
"""
|
140 |
+
#### Selecting the right UI
|
141 |
+
|
142 |
+
[Streamlit](https://docs.streamlit.io/) and [Gradio](https://www.gradio.app/docs/) are among the popular options to share a LLM-based application.
|
143 |
+
|
144 |
+
I chose Streamlit for its script-writing development experience and integrated webapp-like UI that supports multi-page app creation.
|
145 |
+
"""
|
146 |
+
)
|
147 |
+
|
148 |
+
st.markdown(
|
149 |
+
"""
|
150 |
+
#### Appendix: Project Working Log and Feature Tracker
|
151 |
+
|
152 |
+
- [GitHub Homepage](https://github.com/fyang0507/my-notion-companion)
|
153 |
+
- [Working Log](https://fredyang0507.notion.site/MyNotionCompanion-ce12513756784d2ab15015582538825e?pvs=4)
|
154 |
+
- [Feature Tracker](https://fredyang0507.notion.site/306e21cfd9fa49b68f7160b2f6692f72?v=789f8ef443f44c96b7cc5f0c99a3a773&pvs=4)
|
155 |
+
"""
|
156 |
+
)
|
pages/3_Motivation.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Ref: https://docs.streamlit.io/knowledge-base/tutorials/build-conversational-apps
|
3 |
+
"""
|
4 |
+
|
5 |
+
import streamlit as st
|
6 |
+
|
7 |
+
st.set_page_config(
|
8 |
+
page_title="Motivation",
|
9 |
+
page_icon="🤨",
|
10 |
+
)
|
11 |
+
|
12 |
+
st.markdown("## So Fred, why did you start this project? 🤨")
|
13 |
+
|
14 |
+
st.markdown(
|
15 |
+
"""
|
16 |
+
As much as I've been a very loyal (but freemium) Notion user, search func in Notion **sucks**. It supports only discrete keyword search with exact match (e.g. it treats Taylor Swift as two words).
|
17 |
+
|
18 |
+
What's even worse is that most of my documents are in Chinese. Most Chinese words consist of
|
19 |
+
multiple characters. If you break them up, you end up with a total different meaning ("上海"=Shanghai, "上"=up,"海"=ocean).
|
20 |
+
"""
|
21 |
+
)
|
22 |
+
|
23 |
+
st.image(
|
24 |
+
"resources/search-limit-chinese.png",
|
25 |
+
caption="tried to search for 天马 Pegasus, but it ends up with searching two discrete characters 天 sky and 马 horse",
|
26 |
+
)
|
27 |
+
|
28 |
+
st.markdown(
|
29 |
+
"""
|
30 |
+
My Notion Compnion is here to help me achieve two things:
|
31 |
+
- to have an improved search experience across my notion databases (200+ documents)
|
32 |
+
- to chat with my Notion documents in natural language
|
33 |
+
"""
|
34 |
+
)
|