Vishnu-add commited on
Commit
5bd1932
1 Parent(s): 3b12eab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +230 -230
app.py CHANGED
@@ -1,231 +1,231 @@
1
- import streamlit as st
2
- from langchain_google_genai import ChatGoogleGenerativeAI
3
- from langchain.output_parsers import CommaSeparatedListOutputParser
4
- from utils import fetch_wordpress_data, extract_text, generate_embeddings
5
- import chromadb, yaml
6
- from langchain_chroma import Chroma
7
- from langchain_community.embeddings.sentence_transformer import (
8
- SentenceTransformerEmbeddings,
9
- )
10
- from langchain_core.prompts import ChatPromptTemplate
11
- from langchain_core.runnables import RunnableParallel, RunnablePassthrough
12
- from langchain_core.output_parsers import StrOutputParser
13
- from dotenv import load_dotenv
14
- load_dotenv()
15
- try:
16
- # Attempt to load configuration data from config.yaml file
17
- with open("./config.yaml", 'r') as file:
18
- config_data = yaml.safe_load(file)
19
- except Exception as e:
20
- # Raise exception if config.yaml file is not found
21
- raise Exception(f"Not able to find the file ./config.yaml")
22
-
23
- # Set Streamlit page layout to wide
24
- st.set_page_config(layout="wide")
25
-
26
- # Initialize Chroma database client
27
- client = chromadb.PersistentClient("./posts_db")
28
- collection_name = config_data['collection_name']
29
- collection = client.get_collection(name=collection_name)
30
-
31
- # Initialize embedding function for sentence transformer
32
- embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
33
-
34
- # Initialize Langchain Chroma retriever
35
- langchain_chroma = Chroma(
36
- client=client,
37
- collection_name=collection_name,
38
- embedding_function=embedding_function,
39
- ).as_retriever()
40
-
41
- # Initialize Chat Google Generative AI model
42
- model = ChatGoogleGenerativeAI(model="gemini-pro")
43
-
44
- def update_vector_database(collection, post_id, embeddings, text):
45
- """
46
- Update the vector database with post ID, embeddings, and text.
47
-
48
- Args:
49
- collection: The collection in the database.
50
- post_id (str): The ID of the post.
51
- embeddings (list): List of embeddings generated from the post text.
52
- text (str): The text of the post.
53
- """
54
- collection.upsert(ids=[str(post_id)], documents=[text], embeddings=[embeddings])
55
-
56
- def fetch_existing_posts(collection):
57
- """
58
- Fetch existing posts from the database.
59
-
60
- Args:
61
- collection: The collection in the database.
62
-
63
- Returns:
64
- list: List of existing posts.
65
- """
66
- # Fetch existing posts from the database or any other storage
67
- existing_posts = collection.get()
68
- return existing_posts
69
-
70
- def update_embeddings_on_new_post(collection):
71
- """
72
- Update embeddings for new posts fetched from WordPress data.
73
-
74
- Args:
75
- collection: The collection in the database.
76
- """
77
-
78
- # Fetch existing posts from the database or any other storage
79
- existing_posts = fetch_existing_posts(collection)
80
- new_posts = fetch_wordpress_data(config_data['site_url'])
81
-
82
- # Compare old and new posts to find the difference
83
- existing_post_ids = set(str(post_id) for post_id in existing_posts['ids'])
84
- new_posts_to_update = [post for post in new_posts if str(post['id']) not in existing_post_ids]
85
-
86
- # Update embeddings for new posts
87
- for post in new_posts_to_update:
88
- # Extract text from post
89
- text = extract_text(post)
90
- # Generate embeddings for the post text
91
- embeddings = generate_embeddings(text)
92
- # Update vector database with post ID and embeddings
93
- update_vector_database(collection,post['id'], embeddings, text)
94
-
95
- def rag_generate_response():
96
- """
97
- Generate a prompt for generating reasoning steps for answering the user query.
98
-
99
- Returns:
100
- ChatPromptTemplate: The generated prompt template.
101
- """
102
- template = """You are tasked with designing a prompt for generating reasoning steps for answering to the user_query in a website. Write a Prompt to generate a series of intermediate thoughts or reasoning steps to answer the query. Avoid providing specific solutions or examples, allowing the LLM to explore different approaches independently. Give the output as a list of steps. eg: [1,2,3,...]
103
-
104
- Question: {user_query}
105
- Previous_context : {previous_context}
106
- """
107
- prompt = ChatPromptTemplate.from_template(template)
108
- return prompt
109
-
110
- def develop_reasoning_steps(user_query, initial_prompt, previous_context):
111
- """
112
- Develop reasoning steps based on the user query, initial prompt, and previous context.
113
-
114
- Args:
115
- user_query (str): The query from the user.
116
- initial_prompt (ChatPromptTemplate): The initial prompt template.
117
- previous_context (str): The previous context.
118
-
119
- Returns:
120
- list: List of thought steps.
121
- """
122
- chain = (
123
- RunnableParallel({"user_query": RunnablePassthrough(), "previous_context": RunnablePassthrough()})
124
- | initial_prompt
125
- | model
126
- | CommaSeparatedListOutputParser()
127
- )
128
- thought_steps = chain.invoke({"user_query" : user_query, "previous_context" : previous_context})
129
- thought_steps = thought_steps[0].split('\n')
130
- return thought_steps
131
-
132
- def refine_response_based_on_thought_steps(user_query, thought_steps):
133
- """
134
- Refine the response based on thought steps.
135
-
136
- Args:
137
- user_query (str): The query from the user.
138
- thought_steps (list): List of thought steps.
139
-
140
- Returns:
141
- str: Final refined response.
142
- """
143
- all_retrieved_content = ""
144
-
145
- for thought_step in thought_steps:
146
- # print(langchain_chroma.invoke(thought_step))
147
- retrieved_content = langchain_chroma.invoke(thought_step)
148
- for i in retrieved_content:
149
- all_retrieved_content+=i.page_content
150
- all_retrieved_content+="\n"
151
- template = """You are a helpful assistant which answers the query from the context. If the context does not provide the answer simply reply I cannot answer this and give a suggestion to refer the website. DO NOT say that 'there is no information in the context' or 'the answer from the context is this.' phrases, instead give directly the solution or answer I cannot answer this and give a suggestion to refer the website or similar kind of text based on the context.:
152
-
153
- query : {user_query}
154
-
155
- context : {context}
156
- """
157
- prompt = ChatPromptTemplate.from_template(template)
158
- reason_chain = (
159
- RunnableParallel({'user_query': RunnablePassthrough(), 'context': RunnablePassthrough()})
160
- | prompt
161
- | model
162
- | StrOutputParser()
163
- )
164
- final_response = reason_chain.invoke({'user_query': user_query ,'context' : all_retrieved_content})
165
- return final_response
166
-
167
- def process_query_with_chain_of_thought(user_query, previous_context):
168
- """
169
- Process the user query using the RAG + COT approach.
170
-
171
- Args:
172
- user_query (str): The query from the user.
173
- previous_context (list): List of previous chat contexts.
174
-
175
- Returns:
176
- tuple: A tuple containing thought steps and final refined response.
177
- """
178
- initial_response = rag_generate_response(user_query) # initial response is the prompt
179
- thought_steps = develop_reasoning_steps(user_query, initial_response, previous_context)
180
- final_response = refine_response_based_on_thought_steps(user_query,thought_steps)
181
- return thought_steps, final_response
182
-
183
- def bot():
184
- """
185
- Streamlit application to run the conversational AI bot.
186
- """
187
- def web_bot():
188
- global persist_directory
189
- if st.button("New Chat 🤖",key="Start New Chat"):
190
- st.session_state.clear()
191
- st.session_state.app = web_bot
192
- st.rerun()
193
-
194
- # Initialize chat history
195
- if "messages" not in st.session_state:
196
- st.session_state.messages = []
197
-
198
-
199
- # Display chat messages from history and rerun
200
- for message in st.session_state.messages:
201
- with st.chat_message(message["role"]):
202
- st.markdown(message["content"])
203
- if message["role"]=="assistant":
204
- for i in message["thought_steps"]:
205
- st.markdown("- " + i)
206
-
207
- # Respond to user input after receiving
208
- if user_query:= st.chat_input("What's up?"):
209
- # Display user messages in chat message container
210
- with st.chat_message("User"):
211
- st.markdown(user_query)
212
- # Add user message to chat history
213
- st.session_state.messages.append({"role": "user", "content": user_query})
214
-
215
- thought_steps, final_response = process_query_with_chain_of_thought(user_query, st.session_state.messages)
216
-
217
-
218
- # Display assistant response in hcat message container
219
- with st.chat_message("assistant"):
220
- for i in thought_steps:
221
- st.markdown("- " + i)
222
- st.markdown(final_response)
223
-
224
- st.session_state.messages.append({"role" : "assistant", "content": final_response, "thought_steps": thought_steps})
225
-
226
- if 'app' not in st.session_state:
227
- st.session_state.app = web_bot
228
-
229
- st.session_state.app()
230
-
231
  bot()
 
1
+ import streamlit as st
2
+ from langchain_google_genai import ChatGoogleGenerativeAI
3
+ from langchain.output_parsers import CommaSeparatedListOutputParser
4
+ from utils import fetch_wordpress_data, extract_text, generate_embeddings
5
+ import chromadb, yaml
6
+ from langchain_chroma import Chroma
7
+ from langchain_community.embeddings.sentence_transformer import (
8
+ SentenceTransformerEmbeddings,
9
+ )
10
+ from langchain_core.prompts import ChatPromptTemplate
11
+ from langchain_core.runnables import RunnableParallel, RunnablePassthrough
12
+ from langchain_core.output_parsers import StrOutputParser
13
+ from dotenv import load_dotenv
14
+ load_dotenv()
15
+ try:
16
+ # Attempt to load configuration data from config.yaml file
17
+ with open("./config.yaml", 'r') as file:
18
+ config_data = yaml.safe_load(file)
19
+ except Exception as e:
20
+ # Raise exception if config.yaml file is not found
21
+ raise Exception(f"Not able to find the file ./config.yaml")
22
+
23
+ # Set Streamlit page layout to wide
24
+ st.set_page_config(layout="wide")
25
+
26
+ # Initialize Chroma database client
27
+ client = chromadb.PersistentClient("./posts_db")
28
+ collection_name = config_data['collection_name']
29
+ collection = client.get_collection(name=collection_name)
30
+
31
+ # Initialize embedding function for sentence transformer
32
+ embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
33
+
34
+ # Initialize Langchain Chroma retriever
35
+ langchain_chroma = Chroma(
36
+ client=client,
37
+ collection_name=collection_name,
38
+ embedding_function=embedding_function,
39
+ ).as_retriever()
40
+
41
+ # Initialize Chat Google Generative AI model
42
+ model = ChatGoogleGenerativeAI(model="gemini-pro")
43
+
44
+ def update_vector_database(collection, post_id, embeddings, text):
45
+ """
46
+ Update the vector database with post ID, embeddings, and text.
47
+
48
+ Args:
49
+ collection: The collection in the database.
50
+ post_id (str): The ID of the post.
51
+ embeddings (list): List of embeddings generated from the post text.
52
+ text (str): The text of the post.
53
+ """
54
+ collection.upsert(ids=[str(post_id)], documents=[text], embeddings=[embeddings])
55
+
56
+ def fetch_existing_posts(collection):
57
+ """
58
+ Fetch existing posts from the database.
59
+
60
+ Args:
61
+ collection: The collection in the database.
62
+
63
+ Returns:
64
+ list: List of existing posts.
65
+ """
66
+ # Fetch existing posts from the database or any other storage
67
+ existing_posts = collection.get()
68
+ return existing_posts
69
+
70
+ def update_embeddings_on_new_post(collection):
71
+ """
72
+ Update embeddings for new posts fetched from WordPress data.
73
+
74
+ Args:
75
+ collection: The collection in the database.
76
+ """
77
+
78
+ # Fetch existing posts from the database or any other storage
79
+ existing_posts = fetch_existing_posts(collection)
80
+ new_posts = fetch_wordpress_data(config_data['site_url'])
81
+
82
+ # Compare old and new posts to find the difference
83
+ existing_post_ids = set(str(post_id) for post_id in existing_posts['ids'])
84
+ new_posts_to_update = [post for post in new_posts if str(post['id']) not in existing_post_ids]
85
+
86
+ # Update embeddings for new posts
87
+ for post in new_posts_to_update:
88
+ # Extract text from post
89
+ text = extract_text(post)
90
+ # Generate embeddings for the post text
91
+ embeddings = generate_embeddings(text)
92
+ # Update vector database with post ID and embeddings
93
+ update_vector_database(collection,post['id'], embeddings, text)
94
+
95
+ def rag_generate_response():
96
+ """
97
+ Generate a prompt for generating reasoning steps for answering the user query.
98
+
99
+ Returns:
100
+ ChatPromptTemplate: The generated prompt template.
101
+ """
102
+ template = """You are tasked with designing a prompt for generating reasoning steps for answering to the user_query in a website. Write a Prompt to generate a series of intermediate thoughts or reasoning steps to answer the query. Avoid providing specific solutions or examples, allowing the LLM to explore different approaches independently. Give the output as a list of steps. eg: [1,2,3,...]
103
+
104
+ Question: {user_query}
105
+ Previous_context : {previous_context}
106
+ """
107
+ prompt = ChatPromptTemplate.from_template(template)
108
+ return prompt
109
+
110
+ def develop_reasoning_steps(user_query, initial_prompt, previous_context):
111
+ """
112
+ Develop reasoning steps based on the user query, initial prompt, and previous context.
113
+
114
+ Args:
115
+ user_query (str): The query from the user.
116
+ initial_prompt (ChatPromptTemplate): The initial prompt template.
117
+ previous_context (str): The previous context.
118
+
119
+ Returns:
120
+ list: List of thought steps.
121
+ """
122
+ chain = (
123
+ RunnableParallel({"user_query": RunnablePassthrough(), "previous_context": RunnablePassthrough()})
124
+ | initial_prompt
125
+ | model
126
+ | CommaSeparatedListOutputParser()
127
+ )
128
+ thought_steps = chain.invoke({"user_query" : user_query, "previous_context" : previous_context})
129
+ thought_steps = thought_steps[0].split('\n')
130
+ return thought_steps
131
+
132
+ def refine_response_based_on_thought_steps(user_query, thought_steps):
133
+ """
134
+ Refine the response based on thought steps.
135
+
136
+ Args:
137
+ user_query (str): The query from the user.
138
+ thought_steps (list): List of thought steps.
139
+
140
+ Returns:
141
+ str: Final refined response.
142
+ """
143
+ all_retrieved_content = ""
144
+
145
+ for thought_step in thought_steps:
146
+ # print(langchain_chroma.invoke(thought_step))
147
+ retrieved_content = langchain_chroma.invoke(thought_step)
148
+ for i in retrieved_content:
149
+ all_retrieved_content+=i.page_content
150
+ all_retrieved_content+="\n"
151
+ template = """You are a helpful assistant which answers the query from the context. If the context does not provide the answer simply reply I cannot answer this and give a suggestion to refer the website. DO NOT say that 'there is no information in the context' or 'the answer from the context is this.' phrases, instead give directly the solution or answer I cannot answer this and give a suggestion to refer the website or similar kind of text based on the context.:
152
+
153
+ query : {user_query}
154
+
155
+ context : {context}
156
+ """
157
+ prompt = ChatPromptTemplate.from_template(template)
158
+ reason_chain = (
159
+ RunnableParallel({'user_query': RunnablePassthrough(), 'context': RunnablePassthrough()})
160
+ | prompt
161
+ | model
162
+ | StrOutputParser()
163
+ )
164
+ final_response = reason_chain.invoke({'user_query': user_query ,'context' : all_retrieved_content})
165
+ return final_response
166
+
167
+ def process_query_with_chain_of_thought(user_query, previous_context):
168
+ """
169
+ Process the user query using the RAG + COT approach.
170
+
171
+ Args:
172
+ user_query (str): The query from the user.
173
+ previous_context (list): List of previous chat contexts.
174
+
175
+ Returns:
176
+ tuple: A tuple containing thought steps and final refined response.
177
+ """
178
+ initial_response = rag_generate_response() # initial response is the prompt
179
+ thought_steps = develop_reasoning_steps(user_query, initial_response, previous_context)
180
+ final_response = refine_response_based_on_thought_steps(user_query,thought_steps)
181
+ return thought_steps, final_response
182
+
183
+ def bot():
184
+ """
185
+ Streamlit application to run the conversational AI bot.
186
+ """
187
+ def web_bot():
188
+ global persist_directory
189
+ if st.button("New Chat 🤖",key="Start New Chat"):
190
+ st.session_state.clear()
191
+ st.session_state.app = web_bot
192
+ st.rerun()
193
+
194
+ # Initialize chat history
195
+ if "messages" not in st.session_state:
196
+ st.session_state.messages = []
197
+
198
+
199
+ # Display chat messages from history and rerun
200
+ for message in st.session_state.messages:
201
+ with st.chat_message(message["role"]):
202
+ st.markdown(message["content"])
203
+ if message["role"]=="assistant":
204
+ for i in message["thought_steps"]:
205
+ st.markdown("- " + i)
206
+
207
+ # Respond to user input after receiving
208
+ if user_query:= st.chat_input("What's up?"):
209
+ # Display user messages in chat message container
210
+ with st.chat_message("User"):
211
+ st.markdown(user_query)
212
+ # Add user message to chat history
213
+ st.session_state.messages.append({"role": "user", "content": user_query})
214
+
215
+ thought_steps, final_response = process_query_with_chain_of_thought(user_query, st.session_state.messages)
216
+
217
+
218
+ # Display assistant response in hcat message container
219
+ with st.chat_message("assistant"):
220
+ for i in thought_steps:
221
+ st.markdown("- " + i)
222
+ st.markdown(final_response)
223
+
224
+ st.session_state.messages.append({"role" : "assistant", "content": final_response, "thought_steps": thought_steps})
225
+
226
+ if 'app' not in st.session_state:
227
+ st.session_state.app = web_bot
228
+
229
+ st.session_state.app()
230
+
231
  bot()