rajeshlion commited on
Commit
495fb87
·
verified ·
1 Parent(s): 06ff26e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -191
app.py CHANGED
@@ -1,171 +1,4 @@
1
 
2
- # import os
3
- # import openai
4
- # from dotenv import load_dotenv
5
- # _ = load_dotenv() # read local .env file
6
-
7
- # import gradio as gr
8
- # from langchain_chroma import Chroma
9
- # from langchain.chains import ConversationalRetrievalChain
10
- # from langchain_openai import OpenAIEmbeddings, ChatOpenAI
11
-
12
- # # Custom class to handle API routing for different models
13
- # class ChatOpenRouter(ChatOpenAI):
14
- # openai_api_base: str
15
- # openai_api_key: str
16
- # model_name: str
17
-
18
- # def __init__(self,
19
- # model_name: str,
20
- # openai_api_key: str = None,
21
- # openai_api_base: str = "https://openrouter.ai/api/v1",
22
- # **kwargs):
23
- # openai_api_key = openai_api_key or os.getenv('OPENROUTER_API_KEY')
24
- # super().__init__(openai_api_base=openai_api_base,
25
- # openai_api_key=openai_api_key,
26
- # model_name=model_name, **kwargs)
27
-
28
- # # Initialize embedding function here
29
- # embedding_function = OpenAIEmbeddings()
30
-
31
- # # Updated cbfs class with dynamic database and model selection
32
- # class cbfs:
33
- # def __init__(self, persist_directory, model_name):
34
- # self.chat_history = []
35
- # self.answer = ""
36
- # self.db_query = ""
37
- # self.db_response = []
38
- # self.panels = []
39
- # # Initialize Chroma and the ConversationalRetrievalChain with the chosen database and model
40
- # db = Chroma(persist_directory=persist_directory, embedding_function=embedding_function)
41
- # retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 3})
42
-
43
- # # Select model dynamically
44
- # if model_name == "GPT-4":
45
- # chosen_llm = ChatOpenAI(model_name="gpt-4-1106-preview", temperature=0)
46
- # elif model_name == "GPT-3.5":
47
- # chosen_llm = ChatOpenAI(model_name="gpt-3.5-turbo-0125", temperature=0)
48
- # elif model_name == "Llama-3 8B":
49
- # chosen_llm = ChatOpenRouter(model_name="meta-llama/llama-3-8b-instruct", temperature=0)
50
- # elif model_name == "Gemini-1.5 Pro":
51
- # chosen_llm = ChatOpenRouter(model_name="google/gemini-pro-1.5", temperature=0)
52
- # elif model_name == "Claude 3 Sonnet":
53
- # chosen_llm = ChatOpenRouter(model_name='anthropic/claude-3-sonnet', temperature=0)
54
- # elif model_name == "Claude 3.5 Sonnet":
55
- # chosen_llm = ChatOpenRouter(model_name='anthropic/claude-3.5-sonnet', temperature=0)
56
- # else:
57
- # # Default model
58
- # chosen_llm = ChatOpenRouter(model_name="meta-llama/llama-3-70b-instruct", temperature=0)
59
- # # chosen_llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
60
-
61
- # self.qa = ConversationalRetrievalChain.from_llm(
62
- # llm=chosen_llm,
63
- # retriever=retriever,
64
- # return_source_documents=True,
65
- # return_generated_question=True,
66
- # )
67
-
68
- # def convchain(self, query):
69
- # if not query:
70
- # return [("User", ""), ("ChatBot", "")]
71
- # result = self.qa.invoke({"question": query, "chat_history": self.chat_history})
72
- # self.chat_history.append((query, result["answer"]))
73
- # self.db_query = result["generated_question"]
74
- # self.db_response = result["source_documents"]
75
- # self.answer = result['answer']
76
- # self.panels.append(["User", query]) # Ensure this is a list of two strings
77
- # self.panels.append(["ChatBot", self.answer]) # Ensure this is a list of two strings
78
- # return self.panels
79
-
80
- # def clr_history(self):
81
- # self.chat_history = []
82
- # self.panels = []
83
- # return self.panels # Clear the chatbot display
84
-
85
- # # Create Gradio interface functions
86
- # def initialize_cbfs(db_choice, model_choice):
87
- # """Initialize cbfs object based on the database and model selection and clear history."""
88
- # if db_choice == "Governance Documents":
89
- # return cbfs(persist_directory='docs/chroma_eg/', model_name=model_choice)
90
- # elif db_choice == "Faculty Handbook":
91
- # return cbfs(persist_directory='docs/chroma_hb/', model_name=model_choice)
92
- # else:
93
- # return None
94
-
95
- # def chat_history(query, db_choice, model_choice, cb):
96
- # """Handles chat submissions. Reminds the user to select a document if none is selected."""
97
- # # cb = initialize_cbfs(db_choice, model_choice) # Reinitialize cbfs
98
- # if cb is None: # If cb is not initialized, remind to select a document
99
- # return [("ChatBot", "Please select a document from the dropdown menu before submitting your query.")], ""
100
- # else:
101
- # return cb.convchain(query), "" # Clear input box by returning empty string
102
-
103
- # def clear_history(cb):
104
- # # cb = initialize_cbfs(db_choice, model_choice) # Reinitialize cbfs to clear history
105
- # if cb is None: # Check if cbfs instance is None
106
- # return [], "" # No error message, simply clear the UI components
107
- # else:
108
- # cb.clr_history()
109
- # return [], ""
110
-
111
- # # Create Gradio UI layout
112
- # with gr.Blocks() as demo:
113
- # # Full-width image at the top
114
- # with gr.Row():
115
- # gr.Image("isu_logo.jpg", elem_id="full_width_image", show_label=False)
116
-
117
- # # Full-width text below the image
118
- # with gr.Row():
119
- # gr.Markdown("<h1 style='text-align: center; font-size: 3.5em;'>Department of Economics</h1>")
120
-
121
- # gr.Markdown("# Faculty Policies & Rules ChatBot")
122
-
123
- # with gr.Row():
124
- # db_choice = gr.Dropdown(["Governance Documents", "Faculty Handbook"], label="Select Document", scale=1)
125
- # model_choice = gr.Dropdown(["GPT-3.5", "GPT-4", "Llama-3 70B", "Llama-3 8B", "Gemini-1.5 Pro", "Claude 3 Sonnet", "Claude 3.5 Sonnet"],
126
- # label="Select Model", scale=1, value = "Llama-3 70B")
127
- # button_clearhistory = gr.Button("Clear History", scale=1)
128
-
129
- # with gr.Row():
130
- # inp = gr.Textbox(placeholder="Enter text here…", scale=8)
131
- # button_submit = gr.Button("Submit", scale=1)
132
-
133
- # output = gr.Chatbot()
134
-
135
- # # Initialize cbfs instance
136
- # cbfs_instance = gr.State(initialize_cbfs(db_choice.value, model_choice.value))
137
-
138
- # # Update cbfs_instance and clear chat history when the dropdown values change
139
- # def update_cbfs_and_clear_history(db_choice, model_choice):
140
- # new_cbfs = initialize_cbfs(db_choice, model_choice)
141
- # if new_cbfs:
142
- # new_cbfs.clr_history()
143
- # return new_cbfs, [], "" # Clear the chatbot display and input box
144
-
145
- # db_choice.change(
146
- # fn=update_cbfs_and_clear_history,
147
- # inputs=[db_choice, model_choice],
148
- # outputs=[cbfs_instance, output, inp]
149
- # )
150
-
151
- # model_choice.change(
152
- # fn=update_cbfs_and_clear_history,
153
- # inputs=[db_choice, model_choice],
154
- # outputs=[cbfs_instance, output, inp]
155
- # )
156
-
157
- # # Define interactions for both submit button and Enter key
158
- # inp.submit(fn=chat_history, inputs=[inp, db_choice, model_choice, cbfs_instance], outputs=[output, inp])
159
- # button_submit.click(fn=chat_history, inputs=[inp, db_choice, model_choice, cbfs_instance], outputs=[output, inp])
160
- # button_clearhistory.click(fn=clear_history, inputs=cbfs_instance, outputs=[output, inp])
161
-
162
-
163
-
164
- # # Launch the Gradio app
165
- # demo.launch()
166
-
167
-
168
- import spaces
169
  import os
170
  import openai
171
  from dotenv import load_dotenv
@@ -175,18 +8,27 @@ import gradio as gr
175
  from langchain_chroma import Chroma
176
  from langchain.chains import ConversationalRetrievalChain
177
  from langchain_openai import OpenAIEmbeddings, ChatOpenAI
178
- from spaces import GPU # Import GPU decorator
179
 
180
  # Custom class to handle API routing for different models
181
  class ChatOpenRouter(ChatOpenAI):
182
- def __init__(self, model_name: str, openai_api_key: str = None, openai_api_base: str = "https://openrouter.ai/api/v1", **kwargs):
 
 
 
 
 
 
 
 
183
  openai_api_key = openai_api_key or os.getenv('OPENROUTER_API_KEY')
184
- super().__init__(openai_api_base=openai_api_base, openai_api_key=openai_api_key, model_name=model_name, **kwargs)
 
 
185
 
186
  # Initialize embedding function here
187
  embedding_function = OpenAIEmbeddings()
188
 
189
- @GPU # Ensure this class runs on the GPU
190
  class cbfs:
191
  def __init__(self, persist_directory, model_name):
192
  self.chat_history = []
@@ -214,6 +56,7 @@ class cbfs:
214
  else:
215
  # Default model
216
  chosen_llm = ChatOpenRouter(model_name="meta-llama/llama-3-70b-instruct", temperature=0)
 
217
 
218
  self.qa = ConversationalRetrievalChain.from_llm(
219
  llm=chosen_llm,
@@ -240,9 +83,8 @@ class cbfs:
240
  return self.panels # Clear the chatbot display
241
 
242
  # Create Gradio interface functions
243
-
244
- def create_cbfs_instance(db_choice, model_choice):
245
- """Create cbfs instance dynamically without using Gradio state."""
246
  if db_choice == "Governance Documents":
247
  return cbfs(persist_directory='docs/chroma_eg/', model_name=model_choice)
248
  elif db_choice == "Faculty Handbook":
@@ -250,21 +92,21 @@ def create_cbfs_instance(db_choice, model_choice):
250
  else:
251
  return None
252
 
253
- def chat_history(query, db_choice, model_choice):
254
  """Handles chat submissions. Reminds the user to select a document if none is selected."""
255
- cb = create_cbfs_instance(db_choice, model_choice)
256
  if cb is None: # If cb is not initialized, remind to select a document
257
  return [("ChatBot", "Please select a document from the dropdown menu before submitting your query.")], ""
258
  else:
259
  return cb.convchain(query), "" # Clear input box by returning empty string
260
 
261
- def clear_history(db_choice, model_choice):
262
- """Clear history dynamically by creating a new cbfs instance."""
263
- cb = create_cbfs_instance(db_choice, model_choice)
264
- if cb is None:
 
 
265
  return [], ""
266
- cb.clr_history()
267
- return [], ""
268
 
269
  # Create Gradio UI layout
270
  with gr.Blocks() as demo:
@@ -281,7 +123,7 @@ with gr.Blocks() as demo:
281
  with gr.Row():
282
  db_choice = gr.Dropdown(["Governance Documents", "Faculty Handbook"], label="Select Document", scale=1)
283
  model_choice = gr.Dropdown(["GPT-3.5", "GPT-4", "Llama-3 70B", "Llama-3 8B", "Gemini-1.5 Pro", "Claude 3 Sonnet", "Claude 3.5 Sonnet"],
284
- label="Select Model", scale=1, value="Llama-3 70B")
285
  button_clearhistory = gr.Button("Clear History", scale=1)
286
 
287
  with gr.Row():
@@ -290,23 +132,36 @@ with gr.Blocks() as demo:
290
 
291
  output = gr.Chatbot()
292
 
293
- # Define interactions for clearing history when dropdowns are changed
 
 
 
 
 
 
 
 
 
294
  db_choice.change(
295
- fn=clear_history,
296
  inputs=[db_choice, model_choice],
297
- outputs=[output, inp]
298
  )
299
 
300
  model_choice.change(
301
- fn=clear_history,
302
  inputs=[db_choice, model_choice],
303
- outputs=[output, inp]
304
  )
305
 
306
  # Define interactions for both submit button and Enter key
307
- inp.submit(fn=chat_history, inputs=[inp, db_choice, model_choice], outputs=[output, inp])
308
- button_submit.click(fn=chat_history, inputs=[inp, db_choice, model_choice], outputs=[output, inp])
309
- button_clearhistory.click(fn=clear_history, inputs=[db_choice, model_choice], outputs=[output, inp])
 
 
310
 
311
  # Launch the Gradio app
312
  demo.launch()
 
 
 
1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import os
3
  import openai
4
  from dotenv import load_dotenv
 
8
  from langchain_chroma import Chroma
9
  from langchain.chains import ConversationalRetrievalChain
10
  from langchain_openai import OpenAIEmbeddings, ChatOpenAI
 
11
 
12
  # Custom class to handle API routing for different models
13
  class ChatOpenRouter(ChatOpenAI):
14
+ openai_api_base: str
15
+ openai_api_key: str
16
+ model_name: str
17
+
18
+ def __init__(self,
19
+ model_name: str,
20
+ openai_api_key: str = None,
21
+ openai_api_base: str = "https://openrouter.ai/api/v1",
22
+ **kwargs):
23
  openai_api_key = openai_api_key or os.getenv('OPENROUTER_API_KEY')
24
+ super().__init__(openai_api_base=openai_api_base,
25
+ openai_api_key=openai_api_key,
26
+ model_name=model_name, **kwargs)
27
 
28
  # Initialize embedding function here
29
  embedding_function = OpenAIEmbeddings()
30
 
31
+ # Updated cbfs class with dynamic database and model selection
32
  class cbfs:
33
  def __init__(self, persist_directory, model_name):
34
  self.chat_history = []
 
56
  else:
57
  # Default model
58
  chosen_llm = ChatOpenRouter(model_name="meta-llama/llama-3-70b-instruct", temperature=0)
59
+ # chosen_llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
60
 
61
  self.qa = ConversationalRetrievalChain.from_llm(
62
  llm=chosen_llm,
 
83
  return self.panels # Clear the chatbot display
84
 
85
  # Create Gradio interface functions
86
+ def initialize_cbfs(db_choice, model_choice):
87
+ """Initialize cbfs object based on the database and model selection and clear history."""
 
88
  if db_choice == "Governance Documents":
89
  return cbfs(persist_directory='docs/chroma_eg/', model_name=model_choice)
90
  elif db_choice == "Faculty Handbook":
 
92
  else:
93
  return None
94
 
95
+ def chat_history(query, db_choice, model_choice, cb):
96
  """Handles chat submissions. Reminds the user to select a document if none is selected."""
97
+ # cb = initialize_cbfs(db_choice, model_choice) # Reinitialize cbfs
98
  if cb is None: # If cb is not initialized, remind to select a document
99
  return [("ChatBot", "Please select a document from the dropdown menu before submitting your query.")], ""
100
  else:
101
  return cb.convchain(query), "" # Clear input box by returning empty string
102
 
103
+ def clear_history(cb):
104
+ # cb = initialize_cbfs(db_choice, model_choice) # Reinitialize cbfs to clear history
105
+ if cb is None: # Check if cbfs instance is None
106
+ return [], "" # No error message, simply clear the UI components
107
+ else:
108
+ cb.clr_history()
109
  return [], ""
 
 
110
 
111
  # Create Gradio UI layout
112
  with gr.Blocks() as demo:
 
123
  with gr.Row():
124
  db_choice = gr.Dropdown(["Governance Documents", "Faculty Handbook"], label="Select Document", scale=1)
125
  model_choice = gr.Dropdown(["GPT-3.5", "GPT-4", "Llama-3 70B", "Llama-3 8B", "Gemini-1.5 Pro", "Claude 3 Sonnet", "Claude 3.5 Sonnet"],
126
+ label="Select Model", scale=1, value = "Llama-3 70B")
127
  button_clearhistory = gr.Button("Clear History", scale=1)
128
 
129
  with gr.Row():
 
132
 
133
  output = gr.Chatbot()
134
 
135
+ # Initialize cbfs instance
136
+ cbfs_instance = gr.State(initialize_cbfs(db_choice.value, model_choice.value))
137
+
138
+ # Update cbfs_instance and clear chat history when the dropdown values change
139
+ def update_cbfs_and_clear_history(db_choice, model_choice):
140
+ new_cbfs = initialize_cbfs(db_choice, model_choice)
141
+ if new_cbfs:
142
+ new_cbfs.clr_history()
143
+ return new_cbfs, [], "" # Clear the chatbot display and input box
144
+
145
  db_choice.change(
146
+ fn=update_cbfs_and_clear_history,
147
  inputs=[db_choice, model_choice],
148
+ outputs=[cbfs_instance, output, inp]
149
  )
150
 
151
  model_choice.change(
152
+ fn=update_cbfs_and_clear_history,
153
  inputs=[db_choice, model_choice],
154
+ outputs=[cbfs_instance, output, inp]
155
  )
156
 
157
  # Define interactions for both submit button and Enter key
158
+ inp.submit(fn=chat_history, inputs=[inp, db_choice, model_choice, cbfs_instance], outputs=[output, inp])
159
+ button_submit.click(fn=chat_history, inputs=[inp, db_choice, model_choice, cbfs_instance], outputs=[output, inp])
160
+ button_clearhistory.click(fn=clear_history, inputs=cbfs_instance, outputs=[output, inp])
161
+
162
+
163
 
164
  # Launch the Gradio app
165
  demo.launch()
166
+
167
+