Thomas Richardson commited on
Commit
6cc2ac1
·
unverified ·
2 Parent(s): 3faaf176a2d7f9

Merge pull request #106 from ttt246/feature/instant_answer_74

Browse files
.gitignore CHANGED
@@ -1,2 +1,3 @@
1
  /Brain/firebase_cred.json
2
  /.idea
 
 
1
  /Brain/firebase_cred.json
2
  /.idea
3
+ Brain/firebase_cred.json
Brain/src/common/program_type.py CHANGED
@@ -21,3 +21,4 @@ class ProgramType:
21
  SCROLL_BOTTOM = "scroll_bottom"
22
  SELECT_ITEM_DETAIL_INFO = "select_item_detail_info"
23
  SELECT_ITEM = "select_item"
 
 
21
  SCROLL_BOTTOM = "scroll_bottom"
22
  SELECT_ITEM_DETAIL_INFO = "select_item_detail_info"
23
  SELECT_ITEM = "select_item"
24
+ MESSAGE = "message"
Brain/src/model/requests/request_model.py CHANGED
@@ -186,6 +186,14 @@ class BrowserItem(BasicReq):
186
  prompt: str
187
 
188
 
 
 
 
 
 
 
 
 
189
  """endpoint /train"""
190
 
191
 
 
186
  prompt: str
187
 
188
 
189
+ """endpoint /browser/ask"""
190
+
191
+
192
+ class BrowserAsk(BasicReq):
193
+ items: list[str]
194
+ prompt: str
195
+
196
+
197
  """endpoint /train"""
198
 
199
 
Brain/src/rising_plugin/guardrails-config/actions/actions.py CHANGED
@@ -92,6 +92,7 @@ async def general_question(query):
92
  page_content = json_query["page_content"]
93
  document_id = json_query["document_id"]
94
  setting = ReqModel(json_query["setting"])
 
95
 
96
  docs.append(Document(page_content=page_content, metadata=""))
97
  """ 1. calling gpt model to categorize for all message"""
@@ -108,8 +109,11 @@ async def general_question(query):
108
  }
109
  """ 2. check program is message to handle it with falcon llm """
110
  if result["program"] == "message":
111
- """FALCON_7B:"""
112
- result["content"] = falcon_llm.query(question=query)
 
 
 
113
  return str(result)
114
  except ValueError as e:
115
  # Check sms and browser query
 
92
  page_content = json_query["page_content"]
93
  document_id = json_query["document_id"]
94
  setting = ReqModel(json_query["setting"])
95
+ is_browser = json_query["is_browser"]
96
 
97
  docs.append(Document(page_content=page_content, metadata=""))
98
  """ 1. calling gpt model to categorize for all message"""
 
109
  }
110
  """ 2. check program is message to handle it with falcon llm """
111
  if result["program"] == "message":
112
+ if is_browser:
113
+ result["program"] = "ask_website"
114
+ else:
115
+ # """FALCON_7B:"""
116
+ result["content"] = falcon_llm.query(question=query)
117
  return str(result)
118
  except ValueError as e:
119
  # Check sms and browser query
Brain/src/rising_plugin/risingplugin.py CHANGED
@@ -57,6 +57,7 @@ def llm_rails(
57
  firebase_app: firebase_admin.App,
58
  query: str,
59
  image_search: bool = True,
 
60
  ) -> Any:
61
  """step 0: convert string to json"""
62
  index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)
@@ -91,6 +92,7 @@ def llm_rails(
91
  image_search=image_search,
92
  page_content=page_content,
93
  document_id=document_id,
 
94
  ),
95
  }
96
  ]
@@ -103,6 +105,7 @@ def processLargeText(
103
  app: any,
104
  chunks: any,
105
  firebase_app: firebase_admin.App,
 
106
  image_search: bool = True,
107
  ):
108
  if len(chunks) == 1:
@@ -112,6 +115,7 @@ def processLargeText(
112
  firebase_app=firebase_app,
113
  query=chunks[0],
114
  image_search=image_search,
 
115
  )
116
  result = json.dumps(message["content"])
117
  return parseJsonFromCompletion(result)
@@ -146,6 +150,7 @@ def processLargeText(
146
  firebase_app=firebase_app,
147
  query=chunk_query,
148
  image_search=image_search,
 
149
  )
150
  else:
151
  last_query = (
@@ -167,6 +172,7 @@ def processLargeText(
167
  firebase_app=firebase_app,
168
  query=last_query,
169
  image_search=image_search,
 
170
  )
171
  result = json.dumps(message["content"])
172
  return parseJsonFromCompletion(result)
@@ -177,6 +183,7 @@ def getCompletion(
177
  query: str,
178
  setting: ReqModel,
179
  firebase_app: firebase_admin.App,
 
180
  image_search: bool = True,
181
  ):
182
  llm = get_llm(model=DEFAULT_GPT_MODEL, setting=setting).get_llm()
@@ -192,6 +199,7 @@ def getCompletion(
192
  chunks=chunks,
193
  image_search=image_search,
194
  firebase_app=firebase_app,
 
195
  )
196
 
197
 
@@ -297,6 +305,7 @@ def rails_input_with_args(
297
  image_search: bool,
298
  page_content: str,
299
  document_id: str,
 
300
  ) -> str:
301
  # convert json with params for rails.
302
  json_query_with_params = {
@@ -305,6 +314,7 @@ def rails_input_with_args(
305
  "page_content": page_content,
306
  "document_id": document_id,
307
  "setting": setting.to_json(),
 
308
  }
309
  return json.dumps(json_query_with_params)
310
 
 
57
  firebase_app: firebase_admin.App,
58
  query: str,
59
  image_search: bool = True,
60
+ is_browser: bool = False,
61
  ) -> Any:
62
  """step 0: convert string to json"""
63
  index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)
 
92
  image_search=image_search,
93
  page_content=page_content,
94
  document_id=document_id,
95
+ is_browser=is_browser,
96
  ),
97
  }
98
  ]
 
105
  app: any,
106
  chunks: any,
107
  firebase_app: firebase_admin.App,
108
+ is_browser: bool = False,
109
  image_search: bool = True,
110
  ):
111
  if len(chunks) == 1:
 
115
  firebase_app=firebase_app,
116
  query=chunks[0],
117
  image_search=image_search,
118
+ is_browser=is_browser,
119
  )
120
  result = json.dumps(message["content"])
121
  return parseJsonFromCompletion(result)
 
150
  firebase_app=firebase_app,
151
  query=chunk_query,
152
  image_search=image_search,
153
+ is_browser=is_browser,
154
  )
155
  else:
156
  last_query = (
 
172
  firebase_app=firebase_app,
173
  query=last_query,
174
  image_search=image_search,
175
+ is_browser=is_browser,
176
  )
177
  result = json.dumps(message["content"])
178
  return parseJsonFromCompletion(result)
 
183
  query: str,
184
  setting: ReqModel,
185
  firebase_app: firebase_admin.App,
186
+ is_browser: bool = False,
187
  image_search: bool = True,
188
  ):
189
  llm = get_llm(model=DEFAULT_GPT_MODEL, setting=setting).get_llm()
 
199
  chunks=chunks,
200
  image_search=image_search,
201
  firebase_app=firebase_app,
202
+ is_browser=is_browser,
203
  )
204
 
205
 
 
305
  image_search: bool,
306
  page_content: str,
307
  document_id: str,
308
+ is_browser: bool,
309
  ) -> str:
310
  # convert json with params for rails.
311
  json_query_with_params = {
 
314
  "page_content": page_content,
315
  "document_id": document_id,
316
  "setting": setting.to_json(),
317
+ "is_browser": is_browser,
318
  }
319
  return json.dumps(json_query_with_params)
320
 
Brain/src/router/api.py CHANGED
@@ -69,18 +69,22 @@ def construct_blueprint_api() -> APIRouter:
69
  # cloud message
70
  cloud_message = CloudMessage(firebase_app=firebase_app)
71
 
 
 
72
  # parsing params
73
  query = data.message
74
  token = setting.token
75
  uuid = setting.uuid
76
  # check browser endpoint
77
- if client_info.is_browser():
78
- query = f"{query} in a web browser"
 
79
 
80
  result = getCompletion(
81
  query=query,
82
  setting=setting,
83
  firebase_app=firebase_app,
 
84
  )
85
 
86
  # check contact querying
 
69
  # cloud message
70
  cloud_message = CloudMessage(firebase_app=firebase_app)
71
 
72
+ # test
73
+
74
  # parsing params
75
  query = data.message
76
  token = setting.token
77
  uuid = setting.uuid
78
  # check browser endpoint
79
+ # if client_info.is_browser():
80
+ # query = f"{query} in a web browser"
81
+ is_browser = client_info.is_browser()
82
 
83
  result = getCompletion(
84
  query=query,
85
  setting=setting,
86
  firebase_app=firebase_app,
87
+ is_browser=is_browser,
88
  )
89
 
90
  # check contact querying
Brain/src/router/browser_router.py CHANGED
@@ -6,6 +6,7 @@ from Brain.src.common.program_type import ProgramType
6
  from Brain.src.common.utils import parseUrlFromStr
7
  from Brain.src.firebase.firebase import firebase_admin_with_setting
8
  from Brain.src.model.requests.request_model import BrowserItem
 
9
  from Brain.src.service.browser_service import BrowserService
10
 
11
  router = APIRouter()
@@ -57,4 +58,29 @@ def construct_blueprint_browser_api() -> APIRouter:
57
  ),
58
  )
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  return router
 
6
  from Brain.src.common.utils import parseUrlFromStr
7
  from Brain.src.firebase.firebase import firebase_admin_with_setting
8
  from Brain.src.model.requests.request_model import BrowserItem
9
+ from Brain.src.model.requests.request_model import BrowserAsk
10
  from Brain.src.service.browser_service import BrowserService
11
 
12
  router = APIRouter()
 
58
  ),
59
  )
60
 
61
+ @router.post("/ask")
62
+ def get_item(data: BrowserAsk):
63
+ # firebase admin init
64
+ try:
65
+ setting, firebase_app = firebase_admin_with_setting(data)
66
+ except BrainException as ex:
67
+ return ex.get_response_exp()
68
+
69
+ try:
70
+ # parsing contacts
71
+ # train contact
72
+ answer = browser_service.query_ask(items=data.items, query=data.prompt)
73
+ except Exception as e:
74
+ if isinstance(e, BrainException):
75
+ return e.get_response_exp()
76
+ return assembler.to_response(400, "Failed to get item in a browser", "")
77
+ return assembler.to_response(
78
+ 200,
79
+ "Getting an item in a browser successfully",
80
+ assembler.to_result_format(
81
+ ProgramType.BrowserType.MESSAGE,
82
+ answer,
83
+ ),
84
+ )
85
+
86
  return router
Brain/src/service/browser_service.py CHANGED
@@ -11,3 +11,12 @@ class BrowserService:
11
  User is trying to '{query}' and it includes the title of the item.
12
  Please return the link of best relatedness of the item with the title from the below data.\n {items}"""
13
  return getCompletionOnly(query=prompt_template)
 
 
 
 
 
 
 
 
 
 
11
  User is trying to '{query}' and it includes the title of the item.
12
  Please return the link of best relatedness of the item with the title from the below data.\n {items}"""
13
  return getCompletionOnly(query=prompt_template)
14
+
15
+ def query_ask(self, items: list[str], query: str) -> str:
16
+ prompt_template = f"""
17
+ User is asking question related to website that users visit. The following is the user's question.
18
+ '{query}'.\n
19
+ Also the below data is list of sentence in the website.
20
+ '{items}' \n
21
+ Please provide me the proper answer.\n """
22
+ return getCompletionOnly(query=prompt_template)
Extension/src/pages/Panel/Panel.jsx CHANGED
@@ -6,8 +6,23 @@ import Message from './Message'
6
  import './Panel.css';
7
 
8
  const {Footer, Content} = Layout;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- let currentATags = []
11
  let prompt = ""
12
 
13
  const Panel = () => {
@@ -16,6 +31,10 @@ const Panel = () => {
16
  const [isLoading, setLoadingStatus] = useState(false);
17
  const chat_box = useRef(null);
18
 
 
 
 
 
19
  const handleQuestionUpdated = (event) => {
20
  if (event.key === "Enter" && !isLoading) {
21
  addMessage(question, true);
@@ -28,6 +47,10 @@ const Panel = () => {
28
  setQuestion(event.target.value);
29
  };
30
 
 
 
 
 
31
  const addMessage = (message, type, isLoading = false) => {
32
  if (message === "") return;
33
 
@@ -45,24 +68,10 @@ const Panel = () => {
45
  }]);
46
  };
47
 
48
- const sendNotification = async () => {
49
- const params = {
50
- "confs": {
51
- "openai_key": "string",
52
- "pinecone_key": "string",
53
- "pinecone_env": "string",
54
- "firebase_key": "string",
55
- "token": "",
56
- "uuid": "",
57
- "settings": {
58
- "temperature": 0.6
59
- }
60
- },
61
- "message": question
62
- }
63
-
64
- setQuestion("")
65
-
66
  const requestOptions = {
67
  method: 'POST', headers: {
68
  'Content-Type': 'application/json'
@@ -70,10 +79,21 @@ const Panel = () => {
70
  }
71
 
72
  setLoadingStatus(true)
73
- const response = await fetch('https://ttt246-brain.hf.space/sendNotification', requestOptions)
74
  const data = await response.json()
75
  setLoadingStatus(false)
76
 
 
 
 
 
 
 
 
 
 
 
 
77
  if (data.result === undefined || data.result == null) {
78
  return
79
  }
@@ -141,20 +161,10 @@ const Panel = () => {
141
  break
142
  case 'select_item_detail_info':
143
  addMessage("I need more detail info to select item", false)
144
- setLoadingStatus(true)
145
- let data = await selectItem()
146
- setLoadingStatus(false)
147
-
148
- console.log(data)
149
-
150
- if(data.result.program === "select_item")
151
- window.open(data.result.content, '_blank', 'noreferrer')
152
- break
153
- case 'select_item':
154
- addMessage("select item", false)
155
  break
156
  case 'ask_website':
157
- askAboutCurrentWebsite();
158
  break
159
  default:
160
  break
@@ -166,44 +176,27 @@ const Panel = () => {
166
 
167
  const selectItem = async () => {
168
  const params = {
169
- "confs": {
170
- "openai_key": "string",
171
- "pinecone_key": "string",
172
- "pinecone_env": "string",
173
- "firebase_key": "string",
174
- "token": "",
175
- "uuid": "",
176
- "settings": {
177
- "temperature": 0.6
178
- }
179
- },
180
  "prompt": prompt,
181
  "items": scrapeATags()
182
  }
183
- console.log(params)
 
 
184
 
185
- const requestOptions = {
186
- method: 'POST', headers: {
187
- 'Content-Type': 'application/json'
188
- }, body: JSON.stringify(params)
 
189
  }
190
-
191
- setLoadingStatus(true)
192
- const response = await fetch('https://ttt246-brain.hf.space/browser/item', requestOptions)
193
- const data = await response.json()
194
- setLoadingStatus(false)
195
-
196
- return data
197
  }
198
 
199
- useEffect(() => {
200
- chat_box.current.scrollTop = chat_box.current.scrollHeight;
201
- }, [messages]);
202
-
203
- useEffect(() => {
204
- currentATags = scrapeATags()
205
- }, [])
206
-
207
  const scrapeATags = () => {
208
  const links = []
209
 
@@ -224,50 +217,15 @@ const Panel = () => {
224
 
225
  const scrapeWebsites = () => {
226
  const data = []
227
-
228
  const tags = document.querySelectorAll(['a', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7'])
229
-
230
  tags.forEach((tag) => {
231
  const content = tag.textContent || ''
232
-
233
- data.push(content)
234
  })
235
-
236
- return data
237
- }
238
-
239
- const askAboutCurrentWebsite = async () => {
240
- const params = {
241
- "confs": {
242
- "openai_key": "string",
243
- "pinecone_key": "string",
244
- "pinecone_env": "string",
245
- "firebase_key": "string",
246
- "token": "",
247
- "uuid": "",
248
- "settings": {
249
- "temperature": 0.6
250
- }
251
- },
252
- "prompt": prompt,
253
- "items": scrapeWebsites()
254
- }
255
-
256
- const requestOptions = {
257
- method: 'POST', headers: {
258
- 'Content-Type': 'application/json'
259
- }, body: JSON.stringify(params)
260
- }
261
-
262
- setLoadingStatus(true)
263
- const response = await fetch('https://ttt246-brain.hf.space/browser/ask_website', requestOptions)
264
- const data = await response.json()
265
- setLoadingStatus(false)
266
-
267
  return data
268
  }
269
 
270
-
271
  return (
272
  <Layout className="main-layout">
273
  <div className="header">
 
6
  import './Panel.css';
7
 
8
  const {Footer, Content} = Layout;
9
+ const confs = {
10
+ "openai_key": "string",
11
+ "pinecone_key": "string",
12
+ "pinecone_env": "string",
13
+ "firebase_key": "string",
14
+ "token": "",
15
+ "uuid": "",
16
+ "settings": {
17
+ "temperature": 0.6
18
+ }
19
+ }
20
+
21
+ const URL_BASE = 'https://ttt246-brain.hf.space/'
22
+ const URL_SEND_NOTIFICATION = URL_BASE + 'sendNotification'
23
+ const URL_BROWSER_ITEM = URL_BASE + 'browser/item'
24
+ const URL_ASK_WEBSITE = URL_BASE + 'browser/ask_website'
25
 
 
26
  let prompt = ""
27
 
28
  const Panel = () => {
 
31
  const [isLoading, setLoadingStatus] = useState(false);
32
  const chat_box = useRef(null);
33
 
34
+ /*
35
+ * methods for states in ui
36
+ * lifecycle methods
37
+ */
38
  const handleQuestionUpdated = (event) => {
39
  if (event.key === "Enter" && !isLoading) {
40
  addMessage(question, true);
 
47
  setQuestion(event.target.value);
48
  };
49
 
50
+ useEffect(() => {
51
+ chat_box.current.scrollTop = chat_box.current.scrollHeight;
52
+ }, [messages]);
53
+
54
  const addMessage = (message, type, isLoading = false) => {
55
  if (message === "") return;
56
 
 
68
  }]);
69
  };
70
 
71
+ /*
72
+ * methods for sending request to server
73
+ */
74
+ const sendRequest = async (params, url) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  const requestOptions = {
76
  method: 'POST', headers: {
77
  'Content-Type': 'application/json'
 
79
  }
80
 
81
  setLoadingStatus(true)
82
+ const response = await fetch(url, requestOptions)
83
  const data = await response.json()
84
  setLoadingStatus(false)
85
 
86
+ return data
87
+ }
88
+
89
+ const sendNotification = async () => {
90
+ const params = {
91
+ "confs": confs,
92
+ "message": question
93
+ }
94
+ setQuestion("")
95
+
96
+ const data = sendRequest(params, URL_SEND_NOTIFICATION)
97
  if (data.result === undefined || data.result == null) {
98
  return
99
  }
 
161
  break
162
  case 'select_item_detail_info':
163
  addMessage("I need more detail info to select item", false)
164
+ selectItem()
 
 
 
 
 
 
 
 
 
 
165
  break
166
  case 'ask_website':
167
+ askAboutCurrentWebsite()
168
  break
169
  default:
170
  break
 
176
 
177
  const selectItem = async () => {
178
  const params = {
179
+ "confs": confs,
 
 
 
 
 
 
 
 
 
 
180
  "prompt": prompt,
181
  "items": scrapeATags()
182
  }
183
+ const data = sendRequest(params, URL_BROWSER_ITEM)
184
+ window.open(data.result.content, '_blank', 'noreferrer')
185
+ }
186
 
187
+ const askAboutCurrentWebsite = async () => {
188
+ const params = {
189
+ "confs": confs,
190
+ "prompt": prompt,
191
+ "items": scrapeWebsites()
192
  }
193
+ const data = sendRequest(params, URL_ASK_WEBSITE)
194
+ addMessage(data.result.content, false)
 
 
 
 
 
195
  }
196
 
197
+ /*
198
+ * methods for scraping websites
199
+ */
 
 
 
 
 
200
  const scrapeATags = () => {
201
  const links = []
202
 
 
217
 
218
  const scrapeWebsites = () => {
219
  const data = []
 
220
  const tags = document.querySelectorAll(['a', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7'])
 
221
  tags.forEach((tag) => {
222
  const content = tag.textContent || ''
223
+ if(content !== '')
224
+ data.push(content)
225
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  return data
227
  }
228
 
 
229
  return (
230
  <Layout className="main-layout">
231
  <div className="header">