Thomas Richardson commited on
Commit
8b96da2
·
unverified ·
2 Parent(s): be73e2d7bca2ed

Merge pull request #84 from ttt246/feature/llm_interface_9

Browse files
Brain/src/common/assembler.py CHANGED
@@ -5,7 +5,13 @@ from Brain.src.common.http_response_codes import responses
5
  from Brain.src.model.basic_model import BasicModel
6
  from Brain.src.model.contact_model import ContactModel
7
  from Brain.src.model.message_model import MessageModel
8
- from Brain.src.model.requests.request_model import ChatRising, SendSMS, TrainContacts
 
 
 
 
 
 
9
  from Brain.src.model.sms_model import SMSModel
10
 
11
 
@@ -58,3 +64,8 @@ class Assembler:
58
 
59
  def to_result_format(self, program: str, content: str) -> Any:
60
  return {"program": program, "content": content}
 
 
 
 
 
 
5
  from Brain.src.model.basic_model import BasicModel
6
  from Brain.src.model.contact_model import ContactModel
7
  from Brain.src.model.message_model import MessageModel
8
+ from Brain.src.model.req_model import ReqModel
9
+ from Brain.src.model.requests.request_model import (
10
+ ChatRising,
11
+ SendSMS,
12
+ TrainContacts,
13
+ BasicReq,
14
+ )
15
  from Brain.src.model.sms_model import SMSModel
16
 
17
 
 
64
 
65
  def to_result_format(self, program: str, content: str) -> Any:
66
  return {"program": program, "content": content}
67
+
68
+ """mapping basic req"""
69
+
70
+ def to_req_model(self, basic_req: BasicReq) -> ReqModel:
71
+ return ReqModel(basic_req.to_json())
Brain/src/common/brain_exception.py CHANGED
@@ -7,10 +7,11 @@ from Brain.src.common.http_response_codes import responses
7
  class BrainException(Exception):
8
  JSON_PARSING_ISSUE_MSG = "Exception occurred in json paring."
9
 
10
- def __init__(self, message: str = "Exception occurred in brain"):
11
  self.message = message
 
12
  super().__init__(self.message)
13
 
14
  def get_response_exp(self) -> Any:
15
- responses[506] = ("Brain Exception", self.message)
16
- return {"message": responses[506], "result": "", "status_code": 506}
 
7
  class BrainException(Exception):
8
  JSON_PARSING_ISSUE_MSG = "Exception occurred in json paring."
9
 
10
+ def __init__(self, message: str = "Exception occurred in brain", code: int = 506):
11
  self.message = message
12
+ self.code = code
13
  super().__init__(self.message)
14
 
15
  def get_response_exp(self) -> Any:
16
+ responses[self.code] = ("Brain Exception", self.message)
17
+ return {"message": responses[self.code], "result": "", "status_code": self.code}
Brain/src/common/http_response_codes.py CHANGED
@@ -49,4 +49,6 @@ responses = {
49
  504: ("Gateway Timeout", "The gateway server did not receive a timely response"),
50
  505: ("HTTP Version Not Supported", "Cannot fulfill request."),
51
  506: ("Brain Exception"),
 
 
52
  }
 
49
  504: ("Gateway Timeout", "The gateway server did not receive a timely response"),
50
  505: ("HTTP Version Not Supported", "Cannot fulfill request."),
51
  506: ("Brain Exception"),
52
+ 507: ("Firebase Connection Error", "Your key is not correct."),
53
+ 508: ("Pinecone Connection Error", "Your key or env is not correct."),
54
  }
Brain/src/common/utils.py CHANGED
@@ -2,7 +2,6 @@ import json
2
  import os
3
  import re
4
 
5
- from firebase_admin import credentials
6
 
7
  # env variables
8
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
@@ -40,17 +39,6 @@ AUTH_TOKEN = os.getenv("TWILIO_AUTH_TOKEN")
40
  HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
41
 
42
 
43
- def get_firebase_cred():
44
- if os.path.exists("Brain/firebase_cred.json"):
45
- file = open("Brain/firebase_cred.json")
46
- cred = json.load(file)
47
- file.close()
48
- return credentials.Certificate(cred)
49
- else:
50
- cred = json.loads(FIREBASE_ENV)
51
- return credentials.Certificate(cred)
52
-
53
-
54
  class ProgramType:
55
  BROWSER = "browser"
56
  ALERT = "alert"
 
2
  import os
3
  import re
4
 
 
5
 
6
  # env variables
7
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
 
39
  HUGGINGFACEHUB_API_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
40
 
41
 
 
 
 
 
 
 
 
 
 
 
 
42
  class ProgramType:
43
  BROWSER = "browser"
44
  ALERT = "alert"
Brain/src/firebase/cloudmessage.py CHANGED
@@ -3,72 +3,84 @@ import sys
3
  import json
4
 
5
  import traceback
6
- from firebase_admin import messaging, firestore
7
 
8
- db = firestore.client()
 
9
 
10
 
11
- def get_tokens():
12
- users_ref = db.collection("users")
13
- docs = users_ref.stream()
14
- registeration_tokens = []
15
- for doc in docs:
16
- registeration_tokens.append(doc.to_dict()["token"])
17
- return registeration_tokens
18
 
 
 
 
 
 
 
 
19
 
20
- def exception_detail(e):
21
- error_class = e.__class__.__name__
22
- detail = e.args[0]
23
- cl, exc, tb = sys.exc_info()
24
- lastCallStack = traceback.extract_tb(tb)[-1]
25
- fileName = lastCallStack[0]
26
- lineNum = lastCallStack[1]
27
- funcName = lastCallStack[2]
28
- errMsg = 'File "{}", line {}, in {}: [{}] {}'.format(
29
- fileName, lineNum, funcName, error_class, detail
30
- )
31
- return errMsg
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- def send_message(notification, token_list):
35
- if token_list == []:
36
- return False, "token_list empty"
37
- if notification.get("title") not in [None, ""]:
38
- notify = messaging.Notification(
39
- title=notification.get("title"), body=notification.get("content", "")
 
 
 
 
 
 
 
 
40
  )
41
- android_notify = messaging.AndroidNotification(
42
- title=notification.get("title"),
43
- body=notification.get("content", ""),
44
- default_sound=True,
45
  )
46
- else:
47
- notify = messaging.Notification(body=notification.get("content", ""))
48
- android_notify = messaging.AndroidNotification(
49
- body=notification.get("content", ""), default_sound=True
 
 
 
 
 
 
50
  )
51
-
52
- multi_msg = messaging.MulticastMessage(
53
- notification=notify,
54
- tokens=token_list,
55
- data={} if "route" not in notification else {"direct": notification["route"]},
56
- android=messaging.AndroidConfig(notification=android_notify, priority="high"),
57
- apns=messaging.APNSConfig(
58
- payload=messaging.APNSPayload(
59
- messaging.Aps(sound=messaging.CriticalSound("default", volume=1.0))
60
- )
61
- ),
62
- )
63
- response = messaging.send_multicast(multi_msg)
64
- failed_tokens = []
65
- if response.failure_count > 0:
66
- responses = response.responses
67
- for idx, resp in enumerate(responses):
68
- if not resp.success:
69
- # The order of responses corresponds to the order of the registration tokens.
70
- failed_tokens.append(token_list[idx])
71
- print("List of tokens that caused failures: {0}".format(failed_tokens))
72
- return True, "send to {} devices, with {} successed, with {} failed.".format(
73
- len(token_list), response.success_count, response.failure_count
74
- )
 
3
  import json
4
 
5
  import traceback
6
+ from typing import Any
7
 
8
+ import firebase_admin
9
+ from firebase_admin import messaging, firestore
10
 
11
 
12
+ class CloudMessage:
13
+ def __init__(self, firebase_app: firebase_admin.App):
14
+ self.firebase_app = firebase_app
15
+ self.db = firestore.client(app=firebase_app)
 
 
 
16
 
17
+ def get_tokens(self):
18
+ users_ref = self.db.collection("users")
19
+ docs = users_ref.stream()
20
+ registeration_tokens = []
21
+ for doc in docs:
22
+ registeration_tokens.append(doc.to_dict()["token"])
23
+ return registeration_tokens
24
 
25
+ def exception_detail(self, e):
26
+ error_class = e.__class__.__name__
27
+ detail = e.args[0]
28
+ cl, exc, tb = sys.exc_info()
29
+ lastCallStack = traceback.extract_tb(tb)[-1]
30
+ fileName = lastCallStack[0]
31
+ lineNum = lastCallStack[1]
32
+ funcName = lastCallStack[2]
33
+ errMsg = 'File "{}", line {}, in {}: [{}] {}'.format(
34
+ fileName, lineNum, funcName, error_class, detail
35
+ )
36
+ return errMsg
37
 
38
+ def send_message(self, notification, token_list):
39
+ if token_list == []:
40
+ return False, "token_list empty"
41
+ if notification.get("title") not in [None, ""]:
42
+ notify = messaging.Notification(
43
+ title=notification.get("title"),
44
+ body=notification.get("content", ""),
45
+ )
46
+ android_notify = messaging.AndroidNotification(
47
+ title=notification.get("title"),
48
+ body=notification.get("content", ""),
49
+ default_sound=True,
50
+ )
51
+ else:
52
+ notify = messaging.Notification(body=notification.get("content", ""))
53
+ android_notify = messaging.AndroidNotification(
54
+ body=notification.get("content", ""), default_sound=True
55
+ )
56
 
57
+ multi_msg = messaging.MulticastMessage(
58
+ notification=notify,
59
+ tokens=token_list,
60
+ data={}
61
+ if "route" not in notification
62
+ else {"direct": notification["route"]},
63
+ android=messaging.AndroidConfig(
64
+ notification=android_notify, priority="high"
65
+ ),
66
+ apns=messaging.APNSConfig(
67
+ payload=messaging.APNSPayload(
68
+ messaging.Aps(sound=messaging.CriticalSound("default", volume=1.0))
69
+ )
70
+ ),
71
  )
72
+ response = messaging.send_multicast(
73
+ multi_msg,
74
+ app=self.firebase_app,
 
75
  )
76
+ failed_tokens = []
77
+ if response.failure_count > 0:
78
+ responses = response.responses
79
+ for idx, resp in enumerate(responses):
80
+ if not resp.success:
81
+ # The order of responses corresponds to the order of the registration tokens.
82
+ failed_tokens.append(token_list[idx])
83
+ print("List of tokens that caused failures: {0}".format(failed_tokens))
84
+ return True, "send to {} devices, with {} successed, with {} failed.".format(
85
+ len(token_list), response.success_count, response.failure_count
86
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Brain/src/firebase/firebase.py CHANGED
@@ -1,8 +1,60 @@
 
 
 
 
1
  import firebase_admin
2
- from Brain.src.common.utils import get_firebase_cred, FIREBASE_STORAGE_BUCKET
 
 
 
 
 
 
 
 
3
 
4
 
5
- def initialize_app():
6
- firebase_admin.initialize_app(
7
- get_firebase_cred(), {"storageBucket": FIREBASE_STORAGE_BUCKET}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from typing import Any
4
+
5
  import firebase_admin
6
+ from firebase_admin import credentials
7
+
8
+ from Brain.src.common.assembler import Assembler
9
+ from Brain.src.common.brain_exception import BrainException
10
+ from Brain.src.common.http_response_codes import responses
11
+ from Brain.src.common.utils import FIREBASE_STORAGE_BUCKET
12
+ from Brain.src.logs import logger
13
+ from Brain.src.model.req_model import ReqModel
14
+ from Brain.src.model.requests.request_model import BasicReq
15
 
16
 
17
+ def initialize_app(setting: ReqModel) -> firebase_admin.App:
18
+ app_name = get_firebase_admin_name(setting.uuid)
19
+ # Check if the app is already initialized
20
+ try:
21
+ app = firebase_admin.get_app(app_name)
22
+ if app is not None:
23
+ # Delete the existing app
24
+ firebase_admin.delete_app(app)
25
+ except Exception as ex:
26
+ logger.warn(
27
+ title="firebase init",
28
+ message=f"this app name: {app_name} does not exist",
29
+ )
30
+ return firebase_admin.initialize_app(
31
+ get_firebase_cred(setting),
32
+ {"storageBucket": FIREBASE_STORAGE_BUCKET},
33
+ name=app_name,
34
  )
35
+
36
+
37
+ def get_firebase_admin_name(uuid: str = ""):
38
+ return f"firebase_admin_{uuid}"
39
+
40
+
41
+ def firebase_admin_with_setting(data: BasicReq):
42
+ # firebase admin init
43
+ assembler = Assembler()
44
+ setting = assembler.to_req_model(data)
45
+ try:
46
+ firebase_app = initialize_app(setting)
47
+ except Exception as ex:
48
+ raise BrainException(code=507, message=responses[507])
49
+ return setting, firebase_app
50
+
51
+
52
+ def get_firebase_cred(setting: ReqModel):
53
+ if os.path.exists("Brain/firebase_cred.json"):
54
+ file = open("Brain/firebase_cred.json")
55
+ cred = json.load(file)
56
+ file.close()
57
+ return credentials.Certificate(cred)
58
+ else:
59
+ cred = json.loads(setting.firebase_key)
60
+ return credentials.Certificate(cred)
Brain/src/model/req_model.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from Brain.src.common.utils import (
4
+ OPENAI_API_KEY,
5
+ PINECONE_KEY,
6
+ PINECONE_ENV,
7
+ FIREBASE_ENV,
8
+ )
9
+
10
+
11
+ class ReqModel:
12
+ class Settings:
13
+ def __init__(self):
14
+ self.temperature: float = 0.6
15
+
16
+ openai_key: str
17
+ pinecone_key: str
18
+ pinecone_env: str
19
+ firebase_key: str
20
+ token: str = ""
21
+ uuid: str = ""
22
+ settings: Settings
23
+
24
+ def __init__(self, data: dict):
25
+ self.openai_key = (
26
+ OPENAI_API_KEY if data["openai_key"] == "" else data["openai_key"]
27
+ )
28
+ self.pinecone_key = (
29
+ PINECONE_KEY if data["pinecone_key"] == "" else data["pinecone_key"]
30
+ )
31
+ self.pinecone_env = (
32
+ PINECONE_ENV if data["pinecone_env"] == "" else data["pinecone_env"]
33
+ )
34
+ self.firebase_key = (
35
+ FIREBASE_ENV if data["firebase_key"] == "" else data["firebase_key"]
36
+ )
37
+ self.token = data["token"]
38
+ self.uuid = data["uuid"]
39
+ self.settings = self.Settings()
40
+ self.settings.temperature = data["settings"]["temperature"]
41
+
42
+ def to_json(self):
43
+ return {
44
+ "openai_key": self.openai_key,
45
+ "pinecone_key": self.pinecone_key,
46
+ "pinecone_env": self.pinecone_env,
47
+ "firebase_key": self.firebase_key,
48
+ "settings": {"temperature": self.settings.temperature},
49
+ "token": self.token,
50
+ "uuid": self.uuid,
51
+ }
Brain/src/model/requests/request_model.py CHANGED
@@ -50,10 +50,44 @@ def get_client_info(request: Request):
50
  return parse_user_agent(user_agent)
51
 
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  class BasicReq(BaseModel):
54
- token: str
55
- uuid: str
56
- model: str = "gpt-3.5-turbo"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
 
59
  """endpoint: /sendNotification"""
@@ -102,7 +136,6 @@ class ChatRising(BasicReq):
102
 
103
  history: list[Format]
104
  user_input: str
105
- model: str
106
 
107
 
108
  """endpoint: /send_sms"""
 
50
  return parse_user_agent(user_agent)
51
 
52
 
53
+ """
54
+ {
55
+ "host_name": string,
56
+ "openai_key": string,
57
+ "pinecone_key": string,
58
+ "pinecone_env": string,
59
+ "firebase_key": string,
60
+ "settings": {
61
+ "temperature": float
62
+ },
63
+ "token": string,
64
+ "uuid": string,
65
+ }
66
+ """
67
+
68
+
69
  class BasicReq(BaseModel):
70
+ class Settings(BaseModel):
71
+ temperature: float = 0.6
72
+
73
+ openai_key: str
74
+ pinecone_key: str
75
+ pinecone_env: str
76
+ firebase_key: str
77
+ token: str = ""
78
+ uuid: str = ""
79
+ settings: Settings
80
+
81
+ def to_json(self):
82
+ return {
83
+ "openai_key": self.openai_key,
84
+ "pinecone_key": self.pinecone_key,
85
+ "pinecone_env": self.pinecone_env,
86
+ "firebase_key": self.firebase_key,
87
+ "settings": {"temperature": self.settings.temperature},
88
+ "token": self.token,
89
+ "uuid": self.uuid,
90
+ }
91
 
92
 
93
  """endpoint: /sendNotification"""
 
136
 
137
  history: list[Format]
138
  user_input: str
 
139
 
140
 
141
  """endpoint: /send_sms"""
Brain/src/rising_plugin/guardrails-config/actions/actions.py CHANGED
@@ -13,7 +13,9 @@
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
 
 
16
  import json
 
17
 
18
  from Brain.src.service.train_service import TrainService
19
  from langchain.docstore.document import Document
@@ -23,7 +25,10 @@ from Brain.src.common.utils import (
23
  COMMAND_SMS_INDEXES,
24
  COMMAND_BROWSER_OPEN,
25
  PINECONE_INDEX_NAME,
 
26
  )
 
 
27
  from Brain.src.rising_plugin.image_embedding import (
28
  query_image_text,
29
  )
@@ -39,6 +44,7 @@ from Brain.src.rising_plugin.llm.llms import (
39
  GPT_4_32K,
40
  GPT_4,
41
  FALCON_7B,
 
42
  )
43
 
44
  from Brain.src.rising_plugin.pinecone_engine import (
@@ -46,68 +52,70 @@ from Brain.src.rising_plugin.pinecone_engine import (
46
  init_pinecone,
47
  )
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  @action()
51
  async def general_question(query):
52
- """step 0: convert string to json"""
53
- index = init_pinecone(PINECONE_INDEX_NAME)
54
- train_service = TrainService()
 
 
55
  try:
56
  json_query = json.loads(query)
57
  except Exception as ex:
58
  raise BrainException(BrainException.JSON_PARSING_ISSUE_MSG)
59
- """step 0-->: parsing params from the json query"""
60
  query = json_query["query"]
61
- model = json_query["model"]
62
- uuid = json_query["uuid"]
63
  image_search = json_query["image_search"]
 
 
 
64
 
65
- """step 1: handle with gpt-4"""
66
-
67
- query_result = get_embed(query)
68
- relatedness_data = index.query(
69
- vector=query_result,
70
- top_k=1,
71
- include_values=False,
72
- namespace=train_service.get_pinecone_index_train_namespace(),
73
  )
74
- documentId = ""
75
- if len(relatedness_data["matches"]) > 0:
76
- documentId = relatedness_data["matches"][0]["id"]
77
- else:
78
- return None
79
- docs = []
80
- document = train_service.read_one_document(documentId)
81
- docs.append(Document(page_content=document["page_content"], metadata=""))
82
-
83
- chain_data = get_llm_chain(model=model).run(input_documents=docs, question=query)
84
- # test
85
- # if model == GPT_3_5_TURBO or model == GPT_4 or model == GPT_4_32K:
86
- # gpt_llm = GptLLM(model=model)
87
- # chain_data = gpt_llm.get_chain().run(input_documents=docs, question=query)
88
- # elif model == FALCON_7B:
89
- # falcon_llm = FalconLLM()
90
- # chain_data = falcon_llm.get_chain().run(question=query)
91
- falcon_llm = FalconLLM()
92
  try:
93
  result = json.loads(chain_data)
94
  # check image query with only its text
95
  if result["program"] == "image":
96
  if image_search:
97
  result["content"] = {
98
- "image_name": query_image_text(result["content"], "", uuid)
99
  }
100
-
101
- # else:
102
- # return result
103
- """check program is message to handle it with falcon llm"""
104
  if result["program"] == "message":
 
105
  result["content"] = falcon_llm.query(question=query)
106
  return str(result)
107
  except ValueError as e:
108
  # Check sms and browser query
109
- if documentId in COMMAND_SMS_INDEXES:
110
  return str({"program": "sms", "content": chain_data})
111
- elif documentId in COMMAND_BROWSER_OPEN:
112
  return str({"program": "browser", "content": "https://google.com"})
 
113
  return str({"program": "message", "content": falcon_llm.query(question=query)})
 
13
  # See the License for the specific language governing permissions and
14
  # limitations under the License.
15
 
16
+ import os
17
  import json
18
+ import numpy as np
19
 
20
  from Brain.src.service.train_service import TrainService
21
  from langchain.docstore.document import Document
 
25
  COMMAND_SMS_INDEXES,
26
  COMMAND_BROWSER_OPEN,
27
  PINECONE_INDEX_NAME,
28
+ DEFAULT_GPT_MODEL,
29
  )
30
+ from Brain.src.model.req_model import ReqModel
31
+ from Brain.src.model.requests.request_model import BasicReq
32
  from Brain.src.rising_plugin.image_embedding import (
33
  query_image_text,
34
  )
 
44
  GPT_4_32K,
45
  GPT_4,
46
  FALCON_7B,
47
+ GPT_LLM_MODELS,
48
  )
49
 
50
  from Brain.src.rising_plugin.pinecone_engine import (
 
52
  init_pinecone,
53
  )
54
 
55
+ """
56
+ query is json string with below format
57
+ {
58
+ "query": string,
59
+ "model": string,
60
+ "uuid": string,
61
+ "image_search": bool,
62
+ "setting": {
63
+ "host_name": string,
64
+ "openai_key": string,
65
+ "pinecone_key": string,
66
+ "pinecone_env": string,
67
+ "firebase_key": string,
68
+ "firebase_env": string
69
+ "settings": {
70
+ "temperature": float
71
+ },
72
+ "token": string,
73
+ "uuid": string,
74
+ }
75
+ }
76
+ """
77
+
78
 
79
  @action()
80
  async def general_question(query):
81
+ """init falcon model"""
82
+ falcon_llm = FalconLLM()
83
+ docs = []
84
+
85
+ """step 0-->: parsing parms from the json query"""
86
  try:
87
  json_query = json.loads(query)
88
  except Exception as ex:
89
  raise BrainException(BrainException.JSON_PARSING_ISSUE_MSG)
 
90
  query = json_query["query"]
 
 
91
  image_search = json_query["image_search"]
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"""
98
+ chain_data = get_llm_chain(model=DEFAULT_GPT_MODEL, setting=setting).run(
99
+ input_documents=docs, question=query
 
 
 
 
100
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  try:
102
  result = json.loads(chain_data)
103
  # check image query with only its text
104
  if result["program"] == "image":
105
  if image_search:
106
  result["content"] = {
107
+ "image_name": query_image_text(result["content"], "", setting)
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
116
+ if document_id in COMMAND_SMS_INDEXES:
117
  return str({"program": "sms", "content": chain_data})
118
+ elif document_id in COMMAND_BROWSER_OPEN:
119
  return str({"program": "browser", "content": "https://google.com"})
120
+
121
  return str({"program": "message", "content": falcon_llm.query(question=query)})
Brain/src/rising_plugin/image_embedding.py CHANGED
@@ -9,6 +9,7 @@ from .pinecone_engine import (
9
  )
10
  from ..model.basic_model import DataStatus
11
  from ..model.image_model import ImageModel
 
12
 
13
 
14
  def get_embeddings():
@@ -16,7 +17,7 @@ def get_embeddings():
16
 
17
 
18
  # def embed_image_text(image_text: str, image_name: str, uuid: str) -> str:
19
- def embed_image_text(image: ImageModel) -> str:
20
  prompt_template = f"""
21
  This is the text about the image.
22
  ###
@@ -24,7 +25,7 @@ def embed_image_text(image: ImageModel) -> str:
24
  """
25
 
26
  embed_image = get_embeddings().embed_query(prompt_template)
27
- index = init_pinecone(PINECONE_INDEX_NAME)
28
 
29
  """create | update | delete in pinecone"""
30
  pinecone_namespace = get_pinecone_index_namespace(image.uuid)
@@ -46,16 +47,16 @@ def embed_image_text(image: ImageModel) -> str:
46
  return "success to embed image text"
47
 
48
 
49
- def query_image_text(image_content, message, uuid):
50
  embed_image = get_embeddings().embed_query(
51
  get_prompt_image_with_message(image_content, message)
52
  )
53
- index = init_pinecone(PINECONE_INDEX_NAME)
54
  relatedness_data = index.query(
55
  vector=embed_image,
56
  top_k=3,
57
  include_values=False,
58
- namespace=get_pinecone_index_namespace(uuid),
59
  )
60
  if len(relatedness_data["matches"]) > 0:
61
  return relatedness_data["matches"][0]["id"]
 
9
  )
10
  from ..model.basic_model import DataStatus
11
  from ..model.image_model import ImageModel
12
+ from ..model.req_model import ReqModel
13
 
14
 
15
  def get_embeddings():
 
17
 
18
 
19
  # def embed_image_text(image_text: str, image_name: str, uuid: str) -> str:
20
+ def embed_image_text(image: ImageModel, setting: ReqModel) -> str:
21
  prompt_template = f"""
22
  This is the text about the image.
23
  ###
 
25
  """
26
 
27
  embed_image = get_embeddings().embed_query(prompt_template)
28
+ index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)
29
 
30
  """create | update | delete in pinecone"""
31
  pinecone_namespace = get_pinecone_index_namespace(image.uuid)
 
47
  return "success to embed image text"
48
 
49
 
50
+ def query_image_text(image_content, message, setting: ReqModel):
51
  embed_image = get_embeddings().embed_query(
52
  get_prompt_image_with_message(image_content, message)
53
  )
54
+ index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)
55
  relatedness_data = index.query(
56
  vector=embed_image,
57
  top_k=3,
58
  include_values=False,
59
+ namespace=get_pinecone_index_namespace(setting.uuid),
60
  )
61
  if len(relatedness_data["matches"]) > 0:
62
  return relatedness_data["matches"][0]["id"]
Brain/src/rising_plugin/llm/gpt_llm.py CHANGED
@@ -9,12 +9,13 @@ from Brain.src.common.utils import (
9
 
10
 
11
  class GptLLM:
12
- def __init__(self, model: str = "gpt-3.5-turbo", temperature: float = 0.6):
 
13
  self.llm = self.init_llm(model=model, temperature=temperature)
14
 
15
- def init_llm(self, model: str = "gpt-3.5-turbo", temperature: float = 0.6) -> Any:
16
  self.llm = ChatOpenAI(
17
- model_name=model, temperature=temperature, openai_api_key=OPENAI_API_KEY
18
  )
19
  return self.llm
20
 
 
9
 
10
 
11
  class GptLLM:
12
+ def __init__(self, openai_key: str, model: str = "gpt-4", temperature: float = 0.6):
13
+ self.key = openai_key
14
  self.llm = self.init_llm(model=model, temperature=temperature)
15
 
16
+ def init_llm(self, model: str = "gpt-4", temperature: float = 0.6) -> Any:
17
  self.llm = ChatOpenAI(
18
+ model_name=model, temperature=temperature, openai_api_key=self.key
19
  )
20
  return self.llm
21
 
Brain/src/rising_plugin/llm/llms.py CHANGED
@@ -2,6 +2,8 @@
2
  from typing import Any
3
 
4
  from Brain.src.common.brain_exception import BrainException
 
 
5
  from Brain.src.rising_plugin.llm.falcon_llm import FalconLLM
6
  from Brain.src.rising_plugin.llm.gpt_llm import GptLLM
7
 
@@ -12,6 +14,7 @@ FALCON_7B = "falcon-7b"
12
 
13
  """list of available model we offer you"""
14
  LLM_MODELS = [GPT_3_5_TURBO, GPT_4, GPT_4_32K, FALCON_7B]
 
15
 
16
 
17
  """exception message"""
@@ -35,23 +38,30 @@ datatype: LLmChain
35
 
36
 
37
  def get_llm_chain(
38
- model: str, temperature: float = 0.6, max_new_tokens: int = 2000
39
  ) -> Any:
40
  if not validate_model(model):
41
  raise BrainException(EXCEPTION_MSG)
42
  """check model"""
43
- llm = get_llm(model=model, temperature=temperature, max_new_tokens=max_new_tokens)
 
 
 
 
 
44
 
45
  return llm.get_chain()
46
 
47
 
48
- def get_llm(model: str, temperature: float = 0.6, max_new_tokens: int = 2000) -> Any:
 
 
49
  if not validate_model(model):
50
  raise BrainException(EXCEPTION_MSG)
51
  """check model"""
52
- llm = GptLLM()
53
  if model == GPT_3_5_TURBO or model == GPT_4 or model == GPT_4_32K:
54
- llm = GptLLM(model=model)
55
  elif model == FALCON_7B:
56
  llm = FalconLLM(temperature=temperature, max_new_tokens=max_new_tokens)
57
  return llm
 
2
  from typing import Any
3
 
4
  from Brain.src.common.brain_exception import BrainException
5
+ from Brain.src.model.req_model import ReqModel
6
+ from Brain.src.model.requests.request_model import BasicReq
7
  from Brain.src.rising_plugin.llm.falcon_llm import FalconLLM
8
  from Brain.src.rising_plugin.llm.gpt_llm import GptLLM
9
 
 
14
 
15
  """list of available model we offer you"""
16
  LLM_MODELS = [GPT_3_5_TURBO, GPT_4, GPT_4_32K, FALCON_7B]
17
+ GPT_LLM_MODELS = [GPT_3_5_TURBO, GPT_4, GPT_4_32K]
18
 
19
 
20
  """exception message"""
 
38
 
39
 
40
  def get_llm_chain(
41
+ setting: ReqModel, model: str, temperature: float = 0.6, max_new_tokens: int = 2000
42
  ) -> Any:
43
  if not validate_model(model):
44
  raise BrainException(EXCEPTION_MSG)
45
  """check model"""
46
+ llm = get_llm(
47
+ model=model,
48
+ temperature=temperature,
49
+ max_new_tokens=max_new_tokens,
50
+ setting=setting,
51
+ )
52
 
53
  return llm.get_chain()
54
 
55
 
56
+ def get_llm(
57
+ setting: ReqModel, model: str, temperature: float = 0.6, max_new_tokens: int = 2000
58
+ ) -> Any:
59
  if not validate_model(model):
60
  raise BrainException(EXCEPTION_MSG)
61
  """check model"""
62
+ llm = GptLLM(openai_key=setting.openai_key)
63
  if model == GPT_3_5_TURBO or model == GPT_4 or model == GPT_4_32K:
64
+ llm = GptLLM(model=model, openai_key=setting.openai_key)
65
  elif model == FALCON_7B:
66
  llm = FalconLLM(temperature=temperature, max_new_tokens=max_new_tokens)
67
  return llm
Brain/src/rising_plugin/pinecone_engine.py CHANGED
@@ -1,12 +1,14 @@
1
  # initialize pinecone
2
  import pinecone
3
  from typing import Any
 
 
 
4
  from ..common.utils import (
5
- PINECONE_KEY,
6
- PINECONE_ENV,
7
  PINECONE_INDEX_NAME,
8
  PINECONE_NAMESPACE,
9
  )
 
10
 
11
  DIMENSION = 1536
12
  METRIC = "cosine"
@@ -14,22 +16,27 @@ POD_TYPE = "p1.x1"
14
 
15
 
16
  # get the existing index in pinecone or create a new one
17
- def init_pinecone(index_name, flag=True):
18
- pinecone.init(api_key=PINECONE_KEY, environment=PINECONE_ENV)
19
- if flag:
20
- return pinecone.Index(index_name)
21
- else:
22
- # create a new index in pinecone
23
- return pinecone.create_index(
24
- index_name, dimension=DIMENSION, metric=METRIC, pod_type=POD_TYPE
25
- )
 
 
 
26
 
27
 
28
  """add item in pinecone"""
29
 
30
 
31
- def add_pinecone(namespace: str, key: str, value: list[float]) -> Any:
32
- index = init_pinecone(PINECONE_INDEX_NAME)
 
 
33
 
34
  upsert_response = index.upsert(
35
  vectors=[{"id": key, "values": value}],
@@ -41,8 +48,10 @@ def add_pinecone(namespace: str, key: str, value: list[float]) -> Any:
41
  """update item in pinecone"""
42
 
43
 
44
- def update_pinecone(namespace: str, key: str, value: list[float]) -> Any:
45
- index = init_pinecone(PINECONE_INDEX_NAME)
 
 
46
 
47
  upsert_response = index.update(
48
  id=key,
@@ -55,8 +64,8 @@ def update_pinecone(namespace: str, key: str, value: list[float]) -> Any:
55
  """delete item in pinecone"""
56
 
57
 
58
- def delete_pinecone(namespace: str, key: str) -> Any:
59
- index = init_pinecone(PINECONE_INDEX_NAME)
60
  delete_response = index.delete(ids=[key], namespace=namespace)
61
  return delete_response
62
 
@@ -64,8 +73,8 @@ def delete_pinecone(namespace: str, key: str) -> Any:
64
  """delete all item in the namespace"""
65
 
66
 
67
- def delete_all_pinecone(namespace: str) -> Any:
68
- index = init_pinecone(PINECONE_INDEX_NAME)
69
  delete_response = index.delete(delete_all=True, namespace=namespace)
70
  return delete_response
71
 
 
1
  # initialize pinecone
2
  import pinecone
3
  from typing import Any
4
+
5
+ from ..common.brain_exception import BrainException
6
+ from ..common.http_response_codes import responses
7
  from ..common.utils import (
 
 
8
  PINECONE_INDEX_NAME,
9
  PINECONE_NAMESPACE,
10
  )
11
+ from ..model.req_model import ReqModel
12
 
13
  DIMENSION = 1536
14
  METRIC = "cosine"
 
16
 
17
 
18
  # get the existing index in pinecone or create a new one
19
+ def init_pinecone(index_name, setting: ReqModel, flag=True):
20
+ try:
21
+ pinecone.init(api_key=setting.pinecone_key, environment=setting.pinecone_env)
22
+ if flag:
23
+ return pinecone.Index(index_name)
24
+ else:
25
+ # create a new index in pinecone
26
+ return pinecone.create_index(
27
+ index_name, dimension=DIMENSION, metric=METRIC, pod_type=POD_TYPE
28
+ )
29
+ except Exception as ex:
30
+ raise BrainException(code=508, message=responses[508])
31
 
32
 
33
  """add item in pinecone"""
34
 
35
 
36
+ def add_pinecone(
37
+ namespace: str, key: str, setting: ReqModel, value: list[float]
38
+ ) -> Any:
39
+ index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)
40
 
41
  upsert_response = index.upsert(
42
  vectors=[{"id": key, "values": value}],
 
48
  """update item in pinecone"""
49
 
50
 
51
+ def update_pinecone(
52
+ setting: ReqModel, namespace: str, key: str, value: list[float]
53
+ ) -> Any:
54
+ index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)
55
 
56
  upsert_response = index.update(
57
  id=key,
 
64
  """delete item in pinecone"""
65
 
66
 
67
+ def delete_pinecone(setting: ReqModel, namespace: str, key: str) -> Any:
68
+ index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)
69
  delete_response = index.delete(ids=[key], namespace=namespace)
70
  return delete_response
71
 
 
73
  """delete all item in the namespace"""
74
 
75
 
76
+ def delete_all_pinecone(setting: ReqModel, namespace: str) -> Any:
77
+ index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=setting)
78
  delete_response = index.delete(delete_all=True, namespace=namespace)
79
  return delete_response
80
 
Brain/src/rising_plugin/risingplugin.py CHANGED
@@ -1,12 +1,15 @@
1
  import os
2
  import json
3
  import datetime
 
 
4
  import openai
5
  import replicate
6
  import textwrap
7
 
8
  from typing import Any
9
 
 
10
  from langchain.chains.question_answering import load_qa_chain
11
  from nemoguardrails.rails import LLMRails, RailsConfig
12
 
@@ -14,17 +17,25 @@ from langchain.chat_models import ChatOpenAI
14
 
15
  from firebase_admin import storage
16
 
 
17
  from .llm.llms import get_llm, GPT_4, FALCON_7B
 
 
 
18
  from ..common.utils import (
19
  OPENAI_API_KEY,
20
  FIREBASE_STORAGE_ROOT,
21
  DEFAULT_GPT_MODEL,
22
  parseJsonFromCompletion,
 
23
  )
24
  from .image_embedding import (
25
  query_image_text,
26
  get_prompt_image_with_message,
27
  )
 
 
 
28
 
29
  # Give the path to the folder containing the rails
30
  file_path = os.path.dirname(os.path.abspath(__file__))
@@ -40,22 +51,67 @@ def getChunks(query: str):
40
  )
41
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  def processLargeText(
44
- app: any, chunks: any, model: str, uuid: str = "", image_search: bool = True
 
 
 
 
45
  ):
46
  if len(chunks) == 1:
47
- message = app.generate(
48
- messages=[
49
- {
50
- "role": "user",
51
- "content": rails_input_with_args(
52
- query=chunks[0],
53
- model=model,
54
- uuid=uuid,
55
- image_search=image_search,
56
- ),
57
- }
58
- ]
59
  )
60
  result = json.dumps(message["content"])
61
  return parseJsonFromCompletion(result)
@@ -84,18 +140,12 @@ def processLargeText(
84
  + "]\n"
85
  + "Remember not answering yet. Just acknowledge you received this part with the message 'Part 1/10 received' and wait for the next part."
86
  )
87
- app.generate(
88
- messages=[
89
- {
90
- "role": "user",
91
- "content": rails_input_with_args(
92
- query=chunk_query,
93
- model=model,
94
- uuid=uuid,
95
- image_search=image_search,
96
- ),
97
- }
98
- ]
99
  )
100
  else:
101
  last_query = (
@@ -111,18 +161,12 @@ def processLargeText(
111
  + "]\n"
112
  + "ALL PART SENT. Now you can continue processing the request."
113
  )
114
- message = app.generate(
115
- messages=[
116
- {
117
- "role": "user",
118
- "content": rails_input_with_args(
119
- query=last_query,
120
- model=model,
121
- uuid=uuid,
122
- image_search=image_search,
123
- ),
124
- }
125
- ]
126
  )
127
  result = json.dumps(message["content"])
128
  return parseJsonFromCompletion(result)
@@ -130,19 +174,24 @@ def processLargeText(
130
 
131
 
132
  def getCompletion(
133
- query,
134
- model=DEFAULT_GPT_MODEL,
135
- uuid="",
136
- image_search=True,
137
  ):
138
- llm = get_llm(model=DEFAULT_GPT_MODEL).get_llm()
 
139
  # Break input text into chunks
140
  chunks = getChunks(query)
141
 
142
  app = LLMRails(config, llm)
143
 
144
  return processLargeText(
145
- app=app, chunks=chunks, model=model, uuid=uuid, image_search=image_search
 
 
 
 
146
  )
147
 
148
 
@@ -156,10 +205,10 @@ def getCompletionOnly(
156
  return chain_data
157
 
158
 
159
- def query_image_ask(image_content, message, uuid):
160
  prompt_template = get_prompt_image_with_message(image_content, message)
161
  try:
162
- data = getCompletion(query=prompt_template, uuid=uuid, image_search=False)
163
  # chain_data = json.loads(data.replace("'", '"'))
164
  # chain_data = json.loads(data)
165
  if data["program"] == "image":
@@ -169,9 +218,9 @@ def query_image_ask(image_content, message, uuid):
169
  return False
170
 
171
 
172
- def getTextFromImage(filename):
173
  # Create a reference to the image file you want to download
174
- bucket = storage.bucket()
175
  blob = bucket.blob(FIREBASE_STORAGE_ROOT.__add__(filename))
176
  download_url = ""
177
 
@@ -214,15 +263,17 @@ response:
214
 
215
 
216
  # Define a content filter function
217
- def filter_guardrails(model: any, query: str):
218
- llm = ChatOpenAI(model_name=model, temperature=0, openai_api_key=OPENAI_API_KEY)
 
 
219
  app = LLMRails(config, llm)
220
 
221
  # split query with chunks
222
  chunks = getChunks(query)
223
 
224
  # get message from guardrails
225
- message = processLargeText(app=app, chunks=chunks, model=model)
226
 
227
  if (
228
  message
@@ -240,13 +291,20 @@ compose json_string for rails input with its arguments
240
  """
241
 
242
 
243
- def rails_input_with_args(query: str, model: str, uuid: str, image_search: bool) -> str:
 
 
 
 
 
 
244
  # convert json with params for rails.
245
  json_query_with_params = {
246
  "query": query,
247
- "model": model,
248
- "uuid": uuid,
249
  "image_search": image_search,
 
 
 
250
  }
251
  return json.dumps(json_query_with_params)
252
 
 
1
  import os
2
  import json
3
  import datetime
4
+
5
+ import firebase_admin
6
  import openai
7
  import replicate
8
  import textwrap
9
 
10
  from typing import Any
11
 
12
+ from langchain import LLMChain
13
  from langchain.chains.question_answering import load_qa_chain
14
  from nemoguardrails.rails import LLMRails, RailsConfig
15
 
 
17
 
18
  from firebase_admin import storage
19
 
20
+ from .csv_embed import get_embed
21
  from .llm.llms import get_llm, GPT_4, FALCON_7B
22
+ from .pinecone_engine import init_pinecone
23
+ from ..common.brain_exception import BrainException
24
+ from ..common.http_response_codes import responses
25
  from ..common.utils import (
26
  OPENAI_API_KEY,
27
  FIREBASE_STORAGE_ROOT,
28
  DEFAULT_GPT_MODEL,
29
  parseJsonFromCompletion,
30
+ PINECONE_INDEX_NAME,
31
  )
32
  from .image_embedding import (
33
  query_image_text,
34
  get_prompt_image_with_message,
35
  )
36
+ from ..model.req_model import ReqModel
37
+ from ..model.requests.request_model import BasicReq
38
+ from ..service.train_service import TrainService
39
 
40
  # Give the path to the folder containing the rails
41
  file_path = os.path.dirname(os.path.abspath(__file__))
 
51
  )
52
 
53
 
54
+ def llm_rails(
55
+ setting: ReqModel,
56
+ rails_app: any,
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)
63
+ train_service = TrainService(firebase_app=firebase_app, setting=setting)
64
+
65
+ """step 1: handle with gpt-4"""
66
+
67
+ query_result = get_embed(query)
68
+ try:
69
+ relatedness_data = index.query(
70
+ vector=query_result,
71
+ top_k=1,
72
+ include_values=False,
73
+ namespace=train_service.get_pinecone_index_train_namespace(),
74
+ )
75
+ except Exception as ex:
76
+ raise BrainException(code=508, message=responses[508])
77
+ if len(relatedness_data["matches"]) == 0:
78
+ return str({"program": "message", "content": ""})
79
+ document_id = relatedness_data["matches"][0]["id"]
80
+
81
+ document = train_service.read_one_document(document_id)
82
+ page_content = document["page_content"]
83
+
84
+ message = rails_app.generate(
85
+ messages=[
86
+ {
87
+ "role": "user",
88
+ "content": rails_input_with_args(
89
+ setting=setting,
90
+ query=query,
91
+ image_search=image_search,
92
+ page_content=page_content,
93
+ document_id=document_id,
94
+ ),
95
+ }
96
+ ]
97
+ )
98
+ return message
99
+
100
+
101
  def processLargeText(
102
+ setting: ReqModel,
103
+ app: any,
104
+ chunks: any,
105
+ firebase_app: firebase_admin.App,
106
+ image_search: bool = True,
107
  ):
108
  if len(chunks) == 1:
109
+ message = llm_rails(
110
+ setting=setting,
111
+ rails_app=app,
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)
 
140
  + "]\n"
141
  + "Remember not answering yet. Just acknowledge you received this part with the message 'Part 1/10 received' and wait for the next part."
142
  )
143
+ llm_rails(
144
+ setting=setting,
145
+ rails_app=app,
146
+ firebase_app=firebase_app,
147
+ query=chunk_query,
148
+ image_search=image_search,
 
 
 
 
 
 
149
  )
150
  else:
151
  last_query = (
 
161
  + "]\n"
162
  + "ALL PART SENT. Now you can continue processing the request."
163
  )
164
+ message = llm_rails(
165
+ setting=setting,
166
+ rails_app=app,
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)
 
174
 
175
 
176
  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()
183
+
184
  # Break input text into chunks
185
  chunks = getChunks(query)
186
 
187
  app = LLMRails(config, llm)
188
 
189
  return processLargeText(
190
+ setting=setting,
191
+ app=app,
192
+ chunks=chunks,
193
+ image_search=image_search,
194
+ firebase_app=firebase_app,
195
  )
196
 
197
 
 
205
  return chain_data
206
 
207
 
208
+ def query_image_ask(image_content, message, setting: ReqModel):
209
  prompt_template = get_prompt_image_with_message(image_content, message)
210
  try:
211
+ data = getCompletion(query=prompt_template, image_search=False, setting=setting)
212
  # chain_data = json.loads(data.replace("'", '"'))
213
  # chain_data = json.loads(data)
214
  if data["program"] == "image":
 
218
  return False
219
 
220
 
221
+ def getTextFromImage(filename: str, firebase_app: firebase_admin.App) -> str:
222
  # Create a reference to the image file you want to download
223
+ bucket = storage.bucket(app=firebase_app)
224
  blob = bucket.blob(FIREBASE_STORAGE_ROOT.__add__(filename))
225
  download_url = ""
226
 
 
263
 
264
 
265
  # Define a content filter function
266
+ def filter_guardrails(setting: ReqModel, query: str):
267
+ llm = ChatOpenAI(
268
+ model_name=DEFAULT_GPT_MODEL, temperature=0, openai_api_key=setting.openai_key
269
+ )
270
  app = LLMRails(config, llm)
271
 
272
  # split query with chunks
273
  chunks = getChunks(query)
274
 
275
  # get message from guardrails
276
+ message = processLargeText(app=app, chunks=chunks, setting=setting)
277
 
278
  if (
279
  message
 
291
  """
292
 
293
 
294
+ def rails_input_with_args(
295
+ setting: ReqModel,
296
+ query: str,
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 = {
303
  "query": query,
 
 
304
  "image_search": image_search,
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
 
Brain/src/router/api.py CHANGED
@@ -1,9 +1,11 @@
1
  import json
2
- import os
3
 
4
  from Brain.src.common.assembler import Assembler
5
  from Brain.src.common.brain_exception import BrainException
6
- from Brain.src.common.utils import ProgramType
 
 
 
7
  from Brain.src.model.image_model import ImageModel
8
  from Brain.src.model.requests.request_model import (
9
  Notification,
@@ -21,9 +23,8 @@ from Brain.src.rising_plugin.risingplugin import (
21
  getCompletion,
22
  getTextFromImage,
23
  query_image_ask,
24
- handle_chat_completion,
25
  )
26
- from Brain.src.firebase.cloudmessage import send_message, get_tokens
27
  from Brain.src.rising_plugin.image_embedding import embed_image_text, query_image_text
28
 
29
  from Brain.src.logs import logger
@@ -35,7 +36,7 @@ from Brain.src.service.feedback_service import FeedbackService
35
  from Brain.src.service.llm.chat_service import ChatService
36
  from Brain.src.service.twilio_service import TwilioService
37
 
38
- from fastapi import APIRouter, Request, Depends
39
 
40
  router = APIRouter()
41
 
@@ -45,9 +46,8 @@ def construct_blueprint_api() -> APIRouter:
45
  assembler = Assembler()
46
 
47
  # Service
48
- feedback_service = FeedbackService()
49
  command_service = CommandService()
50
- contacts_service = ContactsService()
51
 
52
  """@generator.response(
53
  status_code=200, schema={"message": "message", "result": "test_result"}
@@ -60,6 +60,16 @@ def construct_blueprint_api() -> APIRouter:
60
  def send_notification(
61
  data: Notification, client_info: ClientInfo = Depends(get_client_info)
62
  ):
 
 
 
 
 
 
 
 
 
 
63
  query = data.message
64
  token = data.token
65
  uuid = data.uuid
@@ -67,10 +77,13 @@ def construct_blueprint_api() -> APIRouter:
67
  if client_info.is_browser():
68
  query = f"{query} in a web browser"
69
 
70
- result = getCompletion(query=query, uuid=uuid)
 
 
71
 
72
  # check contact querying
73
  try:
 
74
  if result["program"] == ProgramType.CONTACT:
75
  # querying contacts to getting its expected results
76
  contacts_results = contacts_service.query_contacts(
@@ -80,7 +93,7 @@ def construct_blueprint_api() -> APIRouter:
80
 
81
  notification = {"title": "alert", "content": json.dumps(result)}
82
 
83
- state, value = send_message(notification, [token])
84
  return assembler.to_response(200, value, result)
85
  except Exception as e:
86
  logger.error(
@@ -103,21 +116,34 @@ def construct_blueprint_api() -> APIRouter:
103
 
104
  @router.post("/uploadImage")
105
  def upload_image(data: UploadImage):
106
- image_model = ImageModel()
107
- token = data.token
 
 
 
 
 
 
 
 
 
108
 
109
- image_model.image_name = data.image_name
110
- image_model.uuid = data.uuid
111
- image_model.status = data.status
112
 
113
- image_model.image_text = getTextFromImage(image_model.image_name)
 
 
114
 
115
- embed_result = embed_image_text(image_model)
116
 
117
- notification = {"title": "alert", "content": embed_result}
118
 
119
- state, value = send_message(notification, [token])
120
- return assembler.to_response(200, value, image_model.to_json())
 
 
121
 
122
  """@generator.response(
123
  status_code=200, schema={"message": "message", "result": "test_result"}
@@ -133,27 +159,40 @@ def construct_blueprint_api() -> APIRouter:
133
 
134
  @router.post("/image_relatedness")
135
  def image_relatedness(data: ImageRelatedness):
 
 
 
 
 
 
 
 
 
136
  image_name = data.image_name
137
  message = data.message
138
  token = data.token
139
  uuid = data.uuid
140
 
141
- image_content = getTextFromImage(image_name)
142
  # check message type
143
  image_response = {}
144
  try:
145
  # check about asking image description with trained data
146
- if query_image_ask(image_content, message, uuid):
 
 
147
  image_response["image_desc"] = image_content
148
  else:
149
- relatedness_data = query_image_text(image_content, message, uuid)
150
 
151
  image_response["image_name"] = relatedness_data
152
  except ValueError as e:
153
  print("image_relatedness parsing error for message chain data")
 
 
154
 
155
  notification = {"title": "alert", "content": json.dumps(image_response)}
156
- state, value = send_message(notification, [token])
157
 
158
  return assembler.to_response(
159
  code=200,
@@ -177,6 +216,12 @@ def construct_blueprint_api() -> APIRouter:
177
  @router.post("/feedback")
178
  def add_feedback(data: Feedback):
179
  try:
 
 
 
 
 
 
180
  token = data.token
181
  uuid = data.uuid
182
 
@@ -193,6 +238,8 @@ def construct_blueprint_api() -> APIRouter:
193
  # add the feedback
194
  feedback_service.add(feedback)
195
  except Exception as e:
 
 
196
  return assembler.to_response(400, "failed to add", "")
197
  return assembler.to_response(200, "added successfully", "")
198
 
@@ -200,8 +247,17 @@ def construct_blueprint_api() -> APIRouter:
200
  status_code=200, schema={"message": "message", "result": "test_result"}
201
  )"""
202
 
203
- @router.get("/feedback/{search}/{rating}")
204
- def get_feedback(search: str, rating: int):
 
 
 
 
 
 
 
 
 
205
  result = feedback_service.get(search, rating)
206
  return assembler.to_response(200, "added successfully", result)
207
 
@@ -209,8 +265,8 @@ def construct_blueprint_api() -> APIRouter:
209
  status_code=200, schema={"message": "message", "result": "test_result"}
210
  )"""
211
 
212
- @router.get("/commands")
213
- def get_commands():
214
  result = command_service.get()
215
  return assembler.to_response(
216
  200, "success", {"program": "help_command", "content": result}
@@ -238,14 +294,21 @@ def construct_blueprint_api() -> APIRouter:
238
 
239
  @router.post("/chat_rising")
240
  def message_agent(data: ChatRising):
 
 
 
 
 
 
 
 
241
  try:
242
  token = data.token
243
  uuid = data.uuid
244
  histories = assembler.to_array_message_model(data.history) # json array
245
  user_input = data.user_input
246
- model = data.model
247
  """init chat service with model"""
248
- chat_service = ChatService(ai_name=uuid, llm_model=model)
249
  # getting chat response from rising ai
250
  assistant_reply = chat_service.chat_with_ai(
251
  prompt="",
@@ -283,6 +346,11 @@ def construct_blueprint_api() -> APIRouter:
283
 
284
  @router.post("/send_sms")
285
  def send_sms(data: SendSMS):
 
 
 
 
 
286
  try:
287
  token = data.token
288
  uuid = data.uuid
@@ -316,6 +384,11 @@ def construct_blueprint_api() -> APIRouter:
316
 
317
  @router.post("/train/contacts")
318
  def train_contacts(data: TrainContacts):
 
 
 
 
 
319
  try:
320
  token = data.token
321
  uuid = data.uuid
@@ -325,8 +398,11 @@ def construct_blueprint_api() -> APIRouter:
325
  for contact in data.contacts:
326
  contacts.append(assembler.to_contact_model(contact))
327
  # train contact
 
328
  contacts_service.train(uuid, contacts)
329
  except Exception as e:
 
 
330
  return assembler.to_response(400, "Failed to train contacts", "")
331
  return assembler.to_response(200, "Trained successfully", "")
332
 
@@ -342,14 +418,22 @@ def construct_blueprint_api() -> APIRouter:
342
 
343
  @router.post("/train/contacts/delete")
344
  def delete_all_contacts(data: BasicReq):
 
 
 
 
 
345
  try:
346
  token = data.token
347
  uuid = data.uuid
348
 
349
  # parsing contacts
350
  # train contact
 
351
  contacts_service.delete_all(uuid)
352
  except Exception as e:
 
 
353
  return assembler.to_response(400, "Failed to delete contacts", "")
354
  return assembler.to_response(
355
  200, "Deleted all contacts from pinecone successfully", ""
 
1
  import json
 
2
 
3
  from Brain.src.common.assembler import Assembler
4
  from Brain.src.common.brain_exception import BrainException
5
+ from Brain.src.common.utils import ProgramType, DEFAULT_GPT_MODEL
6
+ from Brain.src.firebase.firebase import (
7
+ firebase_admin_with_setting,
8
+ )
9
  from Brain.src.model.image_model import ImageModel
10
  from Brain.src.model.requests.request_model import (
11
  Notification,
 
23
  getCompletion,
24
  getTextFromImage,
25
  query_image_ask,
 
26
  )
27
+ from Brain.src.firebase.cloudmessage import CloudMessage
28
  from Brain.src.rising_plugin.image_embedding import embed_image_text, query_image_text
29
 
30
  from Brain.src.logs import logger
 
36
  from Brain.src.service.llm.chat_service import ChatService
37
  from Brain.src.service.twilio_service import TwilioService
38
 
39
+ from fastapi import APIRouter, Depends
40
 
41
  router = APIRouter()
42
 
 
46
  assembler = Assembler()
47
 
48
  # Service
49
+
50
  command_service = CommandService()
 
51
 
52
  """@generator.response(
53
  status_code=200, schema={"message": "message", "result": "test_result"}
 
60
  def send_notification(
61
  data: Notification, client_info: ClientInfo = Depends(get_client_info)
62
  ):
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
+ # cloud message
70
+ cloud_message = CloudMessage(firebase_app=firebase_app)
71
+
72
+ # parsing params
73
  query = data.message
74
  token = data.token
75
  uuid = data.uuid
 
77
  if client_info.is_browser():
78
  query = f"{query} in a web browser"
79
 
80
+ result = getCompletion(
81
+ query=query, setting=assembler.to_req_model(data), firebase_app=firebase_app
82
+ )
83
 
84
  # check contact querying
85
  try:
86
+ contacts_service = ContactsService(setting=setting)
87
  if result["program"] == ProgramType.CONTACT:
88
  # querying contacts to getting its expected results
89
  contacts_results = contacts_service.query_contacts(
 
93
 
94
  notification = {"title": "alert", "content": json.dumps(result)}
95
 
96
+ state, value = cloud_message.send_message(notification, [token])
97
  return assembler.to_response(200, value, result)
98
  except Exception as e:
99
  logger.error(
 
116
 
117
  @router.post("/uploadImage")
118
  def upload_image(data: UploadImage):
119
+ # firebase admin init
120
+ try:
121
+ setting, firebase_app = firebase_admin_with_setting(data)
122
+ except BrainException as ex:
123
+ return ex.get_response_exp()
124
+ # cloud message
125
+ try:
126
+ cloud_message = CloudMessage(firebase_app=firebase_app)
127
+
128
+ image_model = ImageModel()
129
+ token = data.token
130
 
131
+ image_model.image_name = data.image_name
132
+ image_model.uuid = data.uuid
133
+ image_model.status = data.status
134
 
135
+ image_model.image_text = getTextFromImage(
136
+ filename=image_model.image_name, firebase_app=firebase_app
137
+ )
138
 
139
+ embed_result = embed_image_text(image=image_model, setting=setting)
140
 
141
+ notification = {"title": "alert", "content": embed_result}
142
 
143
+ state, value = cloud_message.send_message(notification, [token])
144
+ return assembler.to_response(200, value, image_model.to_json())
145
+ except BrainException as ex:
146
+ return ex.get_response_exp()
147
 
148
  """@generator.response(
149
  status_code=200, schema={"message": "message", "result": "test_result"}
 
159
 
160
  @router.post("/image_relatedness")
161
  def image_relatedness(data: ImageRelatedness):
162
+ # firebase admin init
163
+ try:
164
+ setting, firebase_app = firebase_admin_with_setting(data)
165
+ except BrainException as ex:
166
+ return ex.get_response_exp()
167
+
168
+ # cloud message
169
+ cloud_message = CloudMessage(firebase_app=firebase_app)
170
+ # parsing params
171
  image_name = data.image_name
172
  message = data.message
173
  token = data.token
174
  uuid = data.uuid
175
 
176
+ image_content = getTextFromImage(filename=image_name, firebase_app=firebase_app)
177
  # check message type
178
  image_response = {}
179
  try:
180
  # check about asking image description with trained data
181
+ if query_image_ask(
182
+ image_content=image_content, message=message, setting=setting
183
+ ):
184
  image_response["image_desc"] = image_content
185
  else:
186
+ relatedness_data = query_image_text(image_content, message, setting)
187
 
188
  image_response["image_name"] = relatedness_data
189
  except ValueError as e:
190
  print("image_relatedness parsing error for message chain data")
191
+ if isinstance(e, BrainException):
192
+ return e.get_response_exp()
193
 
194
  notification = {"title": "alert", "content": json.dumps(image_response)}
195
+ state, value = cloud_message.send_message(notification, [token])
196
 
197
  return assembler.to_response(
198
  code=200,
 
216
  @router.post("/feedback")
217
  def add_feedback(data: Feedback):
218
  try:
219
+ # firebase admin init
220
+ setting, firebase_app = firebase_admin_with_setting(data)
221
+
222
+ # cloud message
223
+ cloud_message = CloudMessage(firebase_app=firebase_app)
224
+ feedback_service = FeedbackService(firebase_app=firebase_app)
225
  token = data.token
226
  uuid = data.uuid
227
 
 
238
  # add the feedback
239
  feedback_service.add(feedback)
240
  except Exception as e:
241
+ if isinstance(e, BrainException):
242
+ return e.get_response_exp()
243
  return assembler.to_response(400, "failed to add", "")
244
  return assembler.to_response(200, "added successfully", "")
245
 
 
247
  status_code=200, schema={"message": "message", "result": "test_result"}
248
  )"""
249
 
250
+ @router.post("/feedback/{search}/{rating}")
251
+ def get_feedback(search: str, rating: int, data: BasicReq):
252
+ # firebase admin init
253
+ try:
254
+ setting, firebase_app = firebase_admin_with_setting(data)
255
+ except BrainException as ex:
256
+ return ex.get_response_exp()
257
+
258
+ # cloud message
259
+ cloud_message = CloudMessage(firebase_app=firebase_app)
260
+ feedback_service = FeedbackService(firebase_app=firebase_app)
261
  result = feedback_service.get(search, rating)
262
  return assembler.to_response(200, "added successfully", result)
263
 
 
265
  status_code=200, schema={"message": "message", "result": "test_result"}
266
  )"""
267
 
268
+ @router.post("/commands")
269
+ def get_commands(data: BasicReq):
270
  result = command_service.get()
271
  return assembler.to_response(
272
  200, "success", {"program": "help_command", "content": result}
 
294
 
295
  @router.post("/chat_rising")
296
  def message_agent(data: ChatRising):
297
+ # firebase admin init
298
+ try:
299
+ setting, firebase_app = firebase_admin_with_setting(data)
300
+ except BrainException as ex:
301
+ return ex.get_response_exp()
302
+
303
+ # cloud message
304
+ cloud_message = CloudMessage(firebase_app=firebase_app)
305
  try:
306
  token = data.token
307
  uuid = data.uuid
308
  histories = assembler.to_array_message_model(data.history) # json array
309
  user_input = data.user_input
 
310
  """init chat service with model"""
311
+ chat_service = ChatService(ai_name=uuid, llm_model=DEFAULT_GPT_MODEL)
312
  # getting chat response from rising ai
313
  assistant_reply = chat_service.chat_with_ai(
314
  prompt="",
 
346
 
347
  @router.post("/send_sms")
348
  def send_sms(data: SendSMS):
349
+ # firebase admin init
350
+ try:
351
+ setting, firebase_app = firebase_admin_with_setting(data)
352
+ except BrainException as ex:
353
+ return assembler.to_response(ex.code, ex.message, "")
354
  try:
355
  token = data.token
356
  uuid = data.uuid
 
384
 
385
  @router.post("/train/contacts")
386
  def train_contacts(data: TrainContacts):
387
+ # firebase admin init
388
+ try:
389
+ setting, firebase_app = firebase_admin_with_setting(data)
390
+ except BrainException as ex:
391
+ return assembler.to_response(ex.code, ex.message, "")
392
  try:
393
  token = data.token
394
  uuid = data.uuid
 
398
  for contact in data.contacts:
399
  contacts.append(assembler.to_contact_model(contact))
400
  # train contact
401
+ contacts_service = ContactsService(setting=setting)
402
  contacts_service.train(uuid, contacts)
403
  except Exception as e:
404
+ if isinstance(e, BrainException):
405
+ return e.get_response_exp()
406
  return assembler.to_response(400, "Failed to train contacts", "")
407
  return assembler.to_response(200, "Trained successfully", "")
408
 
 
418
 
419
  @router.post("/train/contacts/delete")
420
  def delete_all_contacts(data: BasicReq):
421
+ # firebase admin init
422
+ try:
423
+ setting, firebase_app = firebase_admin_with_setting(data)
424
+ except BrainException as ex:
425
+ return assembler.to_response(ex.code, ex.message, "")
426
  try:
427
  token = data.token
428
  uuid = data.uuid
429
 
430
  # parsing contacts
431
  # train contact
432
+ contacts_service = ContactsService(setting=setting)
433
  contacts_service.delete_all(uuid)
434
  except Exception as e:
435
+ if isinstance(e, BrainException):
436
+ return e.get_response_exp()
437
  return assembler.to_response(400, "Failed to delete contacts", "")
438
  return assembler.to_response(
439
  200, "Deleted all contacts from pinecone successfully", ""
Brain/src/router/browser_router.py CHANGED
@@ -1,8 +1,10 @@
1
  from fastapi import APIRouter, Request, Depends
2
 
3
  from Brain.src.common.assembler import Assembler
 
4
  from Brain.src.common.program_type import ProgramType
5
  from Brain.src.common.utils import parseUrlFromStr
 
6
  from Brain.src.model.requests.request_model import BrowserItem
7
  from Brain.src.service.browser_service import BrowserService
8
 
@@ -28,6 +30,12 @@ def construct_blueprint_browser_api() -> APIRouter:
28
 
29
  @router.post("/item")
30
  def get_item(data: BrowserItem):
 
 
 
 
 
 
31
  item_link = ""
32
  try:
33
  token = data.token
@@ -37,6 +45,8 @@ def construct_blueprint_browser_api() -> APIRouter:
37
  # train contact
38
  item_link = browser_service.query_item(items=data.items, query=data.prompt)
39
  except Exception as e:
 
 
40
  return assembler.to_response(400, "Failed to get item in a browser", "")
41
  return assembler.to_response(
42
  200,
 
1
  from fastapi import APIRouter, Request, Depends
2
 
3
  from Brain.src.common.assembler import Assembler
4
+ from Brain.src.common.brain_exception import BrainException
5
  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
 
 
30
 
31
  @router.post("/item")
32
  def get_item(data: BrowserItem):
33
+ # firebase admin init
34
+ try:
35
+ setting, firebase_app = firebase_admin_with_setting(data)
36
+ except BrainException as ex:
37
+ return ex.get_response_exp()
38
+
39
  item_link = ""
40
  try:
41
  token = data.token
 
45
  # train contact
46
  item_link = browser_service.query_item(items=data.items, query=data.prompt)
47
  except Exception as e:
48
+ if isinstance(e, BrainException):
49
+ return e.get_response_exp()
50
  return assembler.to_response(400, "Failed to get item in a browser", "")
51
  return assembler.to_response(
52
  200,
Brain/src/router/train_router.py CHANGED
@@ -1,8 +1,11 @@
1
  from fastapi import APIRouter
2
 
3
  from Brain.src.common.assembler import Assembler
 
 
4
  from Brain.src.model.requests.request_model import (
5
  Document,
 
6
  )
7
  from Brain.src.service.train_service import TrainService
8
 
@@ -13,15 +16,19 @@ def construct_blueprint_train_api() -> APIRouter:
13
  # Assembler
14
  assembler = Assembler()
15
 
16
- # Services
17
- train_service = TrainService()
18
-
19
  """@generator.response(
20
  status_code=200, schema={"message": "message", "result": "test_result"}
21
  )"""
22
 
23
  @router.get("")
24
- def read_all_documents():
 
 
 
 
 
 
 
25
  try:
26
  result = train_service.read_all_documents()
27
  except Exception as e:
@@ -31,8 +38,15 @@ def construct_blueprint_train_api() -> APIRouter:
31
  """@generator.response( status_code=200, schema={"message": "message", "result": {"document_id": "document_id",
32
  "page_content":"page_content"}} )"""
33
 
34
- @router.get("/all")
35
- def train_all_documents():
 
 
 
 
 
 
 
36
  try:
37
  result = train_service.train_all_documents()
38
  except Exception as e:
@@ -42,8 +56,15 @@ def construct_blueprint_train_api() -> APIRouter:
42
  """@generator.response( status_code=200, schema={"message": "message", "result": {"document_id": "document_id",
43
  "page_content":"page_content"}} )"""
44
 
45
- @router.get("/{document_id}")
46
- def read_one_document(document_id: str):
 
 
 
 
 
 
 
47
  if document_id != "all":
48
  try:
49
  result = train_service.read_one_document(document_id)
@@ -63,6 +84,13 @@ def construct_blueprint_train_api() -> APIRouter:
63
 
64
  @router.post("")
65
  def create_document_train(data: Document):
 
 
 
 
 
 
 
66
  try:
67
  result = train_service.create_one_document(data.page_content)
68
  except Exception as e:
@@ -84,6 +112,13 @@ def construct_blueprint_train_api() -> APIRouter:
84
 
85
  @router.put("")
86
  def update_one_document(data: Document):
 
 
 
 
 
 
 
87
  try:
88
  result = train_service.update_one_document(
89
  data.document_id, data.page_content
@@ -103,11 +138,20 @@ def construct_blueprint_train_api() -> APIRouter:
103
  )
104
  @generator.response( status_code=200, schema={"message": "message", "result": {"document_id": "document_id"}} )"""
105
 
106
- @router.delete("/{document_id}")
107
- def delete_one_document(document_id: str):
 
 
 
 
 
 
 
108
  try:
109
  result = train_service.delete_one_document(document_id)
110
  except Exception as e:
 
 
111
  return assembler.to_response(400, "fail to delete one train", "")
112
  return assembler.to_response(
113
  200, "deleted one document and train data successfully", result
 
1
  from fastapi import APIRouter
2
 
3
  from Brain.src.common.assembler import Assembler
4
+ from Brain.src.common.brain_exception import BrainException
5
+ from Brain.src.firebase.firebase import firebase_admin_with_setting
6
  from Brain.src.model.requests.request_model import (
7
  Document,
8
+ BasicReq,
9
  )
10
  from Brain.src.service.train_service import TrainService
11
 
 
16
  # Assembler
17
  assembler = Assembler()
18
 
 
 
 
19
  """@generator.response(
20
  status_code=200, schema={"message": "message", "result": "test_result"}
21
  )"""
22
 
23
  @router.get("")
24
+ def read_all_documents(data: BasicReq):
25
+ # parsing params
26
+ try:
27
+ setting, firebase_app = firebase_admin_with_setting(data)
28
+ except BrainException as ex:
29
+ return ex.get_response_exp()
30
+ # Services
31
+ train_service = TrainService(firebase_app=firebase_app, setting=setting)
32
  try:
33
  result = train_service.read_all_documents()
34
  except Exception as e:
 
38
  """@generator.response( status_code=200, schema={"message": "message", "result": {"document_id": "document_id",
39
  "page_content":"page_content"}} )"""
40
 
41
+ @router.post("/all")
42
+ def train_all_documents(data: BasicReq):
43
+ # parsing params
44
+ try:
45
+ setting, firebase_app = firebase_admin_with_setting(data)
46
+ except BrainException as ex:
47
+ return ex.get_response_exp()
48
+ # Services
49
+ train_service = TrainService(firebase_app=firebase_app, setting=setting)
50
  try:
51
  result = train_service.train_all_documents()
52
  except Exception as e:
 
56
  """@generator.response( status_code=200, schema={"message": "message", "result": {"document_id": "document_id",
57
  "page_content":"page_content"}} )"""
58
 
59
+ @router.post("/{document_id}")
60
+ def read_one_document(document_id: str, data: BasicReq):
61
+ # parsing params
62
+ try:
63
+ setting, firebase_app = firebase_admin_with_setting(data)
64
+ except BrainException as ex:
65
+ return ex.get_response_exp()
66
+ # Services
67
+ train_service = TrainService(firebase_app=firebase_app, setting=setting)
68
  if document_id != "all":
69
  try:
70
  result = train_service.read_one_document(document_id)
 
84
 
85
  @router.post("")
86
  def create_document_train(data: Document):
87
+ # parsing params
88
+ try:
89
+ setting, firebase_app = firebase_admin_with_setting(data)
90
+ except BrainException as ex:
91
+ return ex.get_response_exp()
92
+ # Services
93
+ train_service = TrainService(firebase_app=firebase_app, setting=setting)
94
  try:
95
  result = train_service.create_one_document(data.page_content)
96
  except Exception as e:
 
112
 
113
  @router.put("")
114
  def update_one_document(data: Document):
115
+ # parsing params
116
+ try:
117
+ setting, firebase_app = firebase_admin_with_setting(data)
118
+ except BrainException as ex:
119
+ return ex.get_response_exp()
120
+ # Services
121
+ train_service = TrainService(firebase_app=firebase_app, setting=setting)
122
  try:
123
  result = train_service.update_one_document(
124
  data.document_id, data.page_content
 
138
  )
139
  @generator.response( status_code=200, schema={"message": "message", "result": {"document_id": "document_id"}} )"""
140
 
141
+ @router.post("/delete/{document_id}")
142
+ def delete_one_document(document_id: str, data: BasicReq):
143
+ # parsing params
144
+ try:
145
+ setting, firebase_app = firebase_admin_with_setting(data)
146
+ except BrainException as ex:
147
+ return ex.get_response_exp()
148
+ # Services
149
+ train_service = TrainService(firebase_app=firebase_app, setting=setting)
150
  try:
151
  result = train_service.delete_one_document(document_id)
152
  except Exception as e:
153
+ if isinstance(e, BrainException):
154
+ return e.get_response_exp()
155
  return assembler.to_response(400, "fail to delete one train", "")
156
  return assembler.to_response(
157
  200, "deleted one document and train data successfully", result
Brain/src/service/contact_service.py CHANGED
@@ -1,6 +1,7 @@
1
  """service to manage contacts"""
2
  from typing import List, Any
3
 
 
4
  from Brain.src.rising_plugin.csv_embed import get_embed
5
  from Brain.src.rising_plugin.pinecone_engine import (
6
  get_pinecone_index_namespace,
@@ -16,6 +17,9 @@ from Brain.src.model.contact_model import ContactModel, ContactStatus
16
 
17
 
18
  class ContactsService:
 
 
 
19
  """train contacts (getting embedding) and update pinecone with embeddings by contact_id
20
  train datatype:
21
  key: contactId
@@ -33,13 +37,23 @@ class ContactsService:
33
  # create | update | delete pinecone
34
  if contact.status == ContactStatus.CREATED:
35
  add_pinecone(
36
- namespace=pinecone_namespace, key=key, value=vectoring_values
 
 
 
37
  )
38
  elif contact.status == ContactStatus.DELETED:
39
- delete_pinecone(namespace=pinecone_namespace, key=key)
 
 
 
 
40
  elif contact.status == ContactStatus.UPDATED:
41
  update_pinecone(
42
- namespace=pinecone_namespace, key=key, value=vectoring_values
 
 
 
43
  )
44
 
45
  """"query contact with search text
@@ -47,7 +61,7 @@ class ContactsService:
47
 
48
  def query_contacts(self, uuid: str, search: str) -> List[str]:
49
  vector_data = get_embed(search)
50
- index = init_pinecone(PINECONE_INDEX_NAME)
51
  relatedness_data = index.query(
52
  vector=vector_data,
53
  top_k=5,
@@ -63,7 +77,9 @@ class ContactsService:
63
  """delete all items in the specific nanespace"""
64
 
65
  def delete_all(self, uuid: str) -> Any:
66
- return delete_all_pinecone(self.get_pinecone_index_namespace(uuid))
 
 
67
 
68
  """get pinecone namespace of pinecone"""
69
 
 
1
  """service to manage contacts"""
2
  from typing import List, Any
3
 
4
+ from Brain.src.model.req_model import ReqModel
5
  from Brain.src.rising_plugin.csv_embed import get_embed
6
  from Brain.src.rising_plugin.pinecone_engine import (
7
  get_pinecone_index_namespace,
 
17
 
18
 
19
  class ContactsService:
20
+ def __init__(self, setting: ReqModel):
21
+ self.setting = setting
22
+
23
  """train contacts (getting embedding) and update pinecone with embeddings by contact_id
24
  train datatype:
25
  key: contactId
 
37
  # create | update | delete pinecone
38
  if contact.status == ContactStatus.CREATED:
39
  add_pinecone(
40
+ namespace=pinecone_namespace,
41
+ key=key,
42
+ value=vectoring_values,
43
+ setting=self.setting,
44
  )
45
  elif contact.status == ContactStatus.DELETED:
46
+ delete_pinecone(
47
+ namespace=pinecone_namespace,
48
+ key=key,
49
+ setting=self.setting,
50
+ )
51
  elif contact.status == ContactStatus.UPDATED:
52
  update_pinecone(
53
+ namespace=pinecone_namespace,
54
+ key=key,
55
+ value=vectoring_values,
56
+ setting=self.setting,
57
  )
58
 
59
  """"query contact with search text
 
61
 
62
  def query_contacts(self, uuid: str, search: str) -> List[str]:
63
  vector_data = get_embed(search)
64
+ index = init_pinecone(index_name=PINECONE_INDEX_NAME, setting=self.setting)
65
  relatedness_data = index.query(
66
  vector=vector_data,
67
  top_k=5,
 
77
  """delete all items in the specific nanespace"""
78
 
79
  def delete_all(self, uuid: str) -> Any:
80
+ return delete_all_pinecone(
81
+ namespace=self.get_pinecone_index_namespace(uuid), setting=self.setting
82
+ )
83
 
84
  """get pinecone namespace of pinecone"""
85
 
Brain/src/service/feedback_service.py CHANGED
@@ -1,5 +1,7 @@
1
  from os import remove
 
2
 
 
3
  from firebase_admin import firestore
4
 
5
 
@@ -9,18 +11,26 @@ from Brain.src.model.feedback_model import FeedbackModel
9
 
10
 
11
  class FeedbackService:
12
- def __init__(self):
13
- self.db = firestore.client()
 
 
 
 
 
 
14
  self.feedbacks_ref = self.db.collection("feedbacks")
15
 
16
  """add a new feedback"""
17
 
18
  def add(self, feedback: FeedbackModel):
 
19
  return self.feedbacks_ref.document().set(feedback.to_json())
20
 
21
  """get list of feedback"""
22
 
23
  def get(self, search, rating):
 
24
  if rating == 0:
25
  query = self.feedbacks_ref.where("rating", "!=", rating)
26
  else:
 
1
  from os import remove
2
+ from typing import Any
3
 
4
+ import firebase_admin
5
  from firebase_admin import firestore
6
 
7
 
 
11
 
12
 
13
  class FeedbackService:
14
+ db: Any
15
+ feedbacks_ref: Any
16
+
17
+ def __init__(self, firebase_app: firebase_admin.App):
18
+ self.firebase_app = firebase_app
19
+
20
+ def init_firestore(self):
21
+ self.db = firestore.client(app=self.firebase_app)
22
  self.feedbacks_ref = self.db.collection("feedbacks")
23
 
24
  """add a new feedback"""
25
 
26
  def add(self, feedback: FeedbackModel):
27
+ self.init_firestore()
28
  return self.feedbacks_ref.document().set(feedback.to_json())
29
 
30
  """get list of feedback"""
31
 
32
  def get(self, search, rating):
33
+ self.init_firestore()
34
  if rating == 0:
35
  query = self.feedbacks_ref.where("rating", "!=", rating)
36
  else:
Brain/src/service/train_service.py CHANGED
@@ -1,11 +1,12 @@
1
  """service to manage trains"""
2
- from typing import List, Any
3
 
 
 
 
4
  from Brain.src.rising_plugin.csv_embed import get_embed
5
  from Brain.src.rising_plugin.pinecone_engine import (
6
  get_pinecone_index_namespace,
7
- update_pinecone,
8
- init_pinecone,
9
  delete_pinecone,
10
  add_pinecone,
11
  delete_all_pinecone,
@@ -28,13 +29,21 @@ class TrainService:
28
  key: document_id
29
  values: {page_content}"""
30
 
31
- def __init__(self):
32
- self.db = firestore.client()
 
 
 
 
 
 
 
33
  self.documents_ref = self.db.collection("documents")
34
 
35
  """read all documents from firestore"""
36
 
37
  def read_all_documents(self):
 
38
  query = self.documents_ref.order_by("timestamp")
39
  docs = query.stream()
40
  result = []
@@ -48,6 +57,7 @@ class TrainService:
48
  """read one document from firestore"""
49
 
50
  def read_one_document(self, document_id: str):
 
51
  doc = self.documents_ref.document(document_id).get()
52
  if doc.exists:
53
  return {
@@ -60,6 +70,7 @@ class TrainService:
60
  """create a new document and train it"""
61
 
62
  def create_one_document(self, page_content: str):
 
63
  # Auto-generate document ID
64
  auto_generated_doc_ref = self.documents_ref.document()
65
  auto_generated_doc_ref.set(to_json(page_content))
@@ -70,6 +81,7 @@ class TrainService:
70
  """update a document by using id and train it"""
71
 
72
  def update_one_document(self, document_id: str, page_content: str):
 
73
  self.documents_ref.document(document_id).update(to_json(page_content))
74
  self.train_one_document(document_id, page_content)
75
  return {"document_id": document_id, "page_content": page_content}
@@ -77,11 +89,13 @@ class TrainService:
77
  """delete a document by using document_id"""
78
 
79
  def delete_one_document(self, document_id: str):
 
80
  self.documents_ref.document(document_id).delete()
81
  self.delete_one_pinecone(document_id)
82
  return {"document_id": document_id}
83
 
84
  def train_all_documents(self) -> str:
 
85
  self.delete_all()
86
  documents = self.read_all_documents()
87
  result = list()
@@ -93,11 +107,17 @@ class TrainService:
93
  value = f'{item["page_content"]}'
94
  # get vectoring data(embedding data)
95
  vectoring_values = get_embed(value)
96
- add_pinecone(namespace=pinecone_namespace, key=key, value=vectoring_values)
 
 
 
 
 
97
 
98
  return "trained all documents successfully"
99
 
100
  def train_one_document(self, document_id: str, page_content: str) -> None:
 
101
  pinecone_namespace = self.get_pinecone_index_namespace()
102
  result = list()
103
  query_result = get_embed(page_content)
@@ -106,16 +126,32 @@ class TrainService:
106
  value = f"{page_content}, {query_result}"
107
  # get vectoring data(embedding data)
108
  vectoring_values = get_embed(value)
109
- add_pinecone(namespace=pinecone_namespace, key=key, value=vectoring_values)
 
 
 
 
 
110
 
111
  def delete_all(self) -> Any:
112
- return delete_all_pinecone(self.get_pinecone_index_namespace())
 
 
 
 
113
 
114
  def delete_one_pinecone(self, document_id: str) -> Any:
115
- return delete_pinecone(self.get_pinecone_index_namespace(), document_id)
 
 
 
 
 
116
 
117
  def get_pinecone_index_namespace(self) -> str:
 
118
  return get_pinecone_index_namespace(f"trains")
119
 
120
  def get_pinecone_index_train_namespace(self) -> str:
 
121
  return get_pinecone_index_namespace(f"trains")
 
1
  """service to manage trains"""
2
+ from typing import Any
3
 
4
+ import firebase_admin
5
+
6
+ from Brain.src.model.req_model import ReqModel
7
  from Brain.src.rising_plugin.csv_embed import get_embed
8
  from Brain.src.rising_plugin.pinecone_engine import (
9
  get_pinecone_index_namespace,
 
 
10
  delete_pinecone,
11
  add_pinecone,
12
  delete_all_pinecone,
 
29
  key: document_id
30
  values: {page_content}"""
31
 
32
+ db: Any
33
+ documents_ref: Any
34
+
35
+ def __init__(self, firebase_app: firebase_admin.App, setting: ReqModel):
36
+ self.firebase_app = firebase_app
37
+ self.setting = setting
38
+
39
+ def init_firestore(self):
40
+ self.db = firestore.client(app=self.firebase_app)
41
  self.documents_ref = self.db.collection("documents")
42
 
43
  """read all documents from firestore"""
44
 
45
  def read_all_documents(self):
46
+ self.init_firestore()
47
  query = self.documents_ref.order_by("timestamp")
48
  docs = query.stream()
49
  result = []
 
57
  """read one document from firestore"""
58
 
59
  def read_one_document(self, document_id: str):
60
+ self.init_firestore()
61
  doc = self.documents_ref.document(document_id).get()
62
  if doc.exists:
63
  return {
 
70
  """create a new document and train it"""
71
 
72
  def create_one_document(self, page_content: str):
73
+ self.init_firestore()
74
  # Auto-generate document ID
75
  auto_generated_doc_ref = self.documents_ref.document()
76
  auto_generated_doc_ref.set(to_json(page_content))
 
81
  """update a document by using id and train it"""
82
 
83
  def update_one_document(self, document_id: str, page_content: str):
84
+ self.init_firestore()
85
  self.documents_ref.document(document_id).update(to_json(page_content))
86
  self.train_one_document(document_id, page_content)
87
  return {"document_id": document_id, "page_content": page_content}
 
89
  """delete a document by using document_id"""
90
 
91
  def delete_one_document(self, document_id: str):
92
+ self.init_firestore()
93
  self.documents_ref.document(document_id).delete()
94
  self.delete_one_pinecone(document_id)
95
  return {"document_id": document_id}
96
 
97
  def train_all_documents(self) -> str:
98
+ self.init_firestore()
99
  self.delete_all()
100
  documents = self.read_all_documents()
101
  result = list()
 
107
  value = f'{item["page_content"]}'
108
  # get vectoring data(embedding data)
109
  vectoring_values = get_embed(value)
110
+ add_pinecone(
111
+ namespace=pinecone_namespace,
112
+ key=key,
113
+ value=vectoring_values,
114
+ setting=self.setting,
115
+ )
116
 
117
  return "trained all documents successfully"
118
 
119
  def train_one_document(self, document_id: str, page_content: str) -> None:
120
+ self.init_firestore()
121
  pinecone_namespace = self.get_pinecone_index_namespace()
122
  result = list()
123
  query_result = get_embed(page_content)
 
126
  value = f"{page_content}, {query_result}"
127
  # get vectoring data(embedding data)
128
  vectoring_values = get_embed(value)
129
+ add_pinecone(
130
+ namespace=pinecone_namespace,
131
+ key=key,
132
+ value=vectoring_values,
133
+ setting=self.setting,
134
+ )
135
 
136
  def delete_all(self) -> Any:
137
+ self.init_firestore()
138
+ return delete_all_pinecone(
139
+ namespace=self.get_pinecone_index_namespace(),
140
+ setting=self.setting,
141
+ )
142
 
143
  def delete_one_pinecone(self, document_id: str) -> Any:
144
+ self.init_firestore()
145
+ return delete_pinecone(
146
+ namespace=self.get_pinecone_index_namespace(),
147
+ key=document_id,
148
+ setting=self.setting,
149
+ )
150
 
151
  def get_pinecone_index_namespace(self) -> str:
152
+ self.init_firestore()
153
  return get_pinecone_index_namespace(f"trains")
154
 
155
  def get_pinecone_index_train_namespace(self) -> str:
156
+ self.init_firestore()
157
  return get_pinecone_index_namespace(f"trains")
Brain/tests/conftest.py CHANGED
@@ -2,10 +2,6 @@ import pytest
2
  from fastapi import FastAPI
3
  from fastapi.testclient import TestClient
4
 
5
- from Brain.src.firebase.firebase import initialize_app
6
-
7
- initialize_app()
8
-
9
 
10
  @pytest.fixture(scope="module")
11
  def test_client():
 
2
  from fastapi import FastAPI
3
  from fastapi.testclient import TestClient
4
 
 
 
 
 
5
 
6
  @pytest.fixture(scope="module")
7
  def test_client():
Brain/tests/functional/test_recipes.py CHANGED
@@ -1,41 +1,63 @@
1
  import re
2
 
 
3
  from Brain.src.firebase.firebase import initialize_app
 
4
  from Brain.src.rising_plugin.risingplugin import getCompletion, getTextFromImage
5
- from Brain.src.firebase.cloudmessage import send_message
6
- from Brain.src.firebase.cloudmessage import get_tokens
7
  from Brain.src.rising_plugin.image_embedding import query_image_text
8
 
9
  TEST_IAMGE_NAME = "0ddffe51-3763-48d9-ab74-2086de529217"
10
  TEST_UUID = "TEST_UUID"
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
 
13
  def test_langchain():
14
  error = "Error happened while analyzing your prompt. Please ask me again"
15
- result = getCompletion(query="open three.js website", uuid=TEST_UUID)
 
 
16
  print(result)
17
  assert result != error
18
 
19
 
20
  def test_image2text():
21
  error = "Error happened while analyzing your prompt. Please ask me again"
22
- result = getTextFromImage(TEST_IAMGE_NAME)
23
  print(result)
24
  assert result != error
25
 
26
 
27
  def test_firebase_cloud_message():
28
- token_list = get_tokens()
 
29
  notification = {"title": "alert", "content": "test"}
30
 
31
  pattern = r"send to \d+ devices, with \d+ successed, with \d+ failed."
32
 
33
- state, value = send_message(notification, token_list)
34
  assert re.match(pattern, value)
35
 
36
 
37
  def test_query_image_text():
38
  error = "Error happened in querying image & text"
39
- result = query_image_text(getTextFromImage(TEST_IAMGE_NAME), "", TEST_UUID)
 
 
 
 
 
 
40
  print(result)
41
  assert result != error
 
1
  import re
2
 
3
+ from Brain.src.firebase.cloudmessage import CloudMessage
4
  from Brain.src.firebase.firebase import initialize_app
5
+ from Brain.src.model.req_model import ReqModel
6
  from Brain.src.rising_plugin.risingplugin import getCompletion, getTextFromImage
 
 
7
  from Brain.src.rising_plugin.image_embedding import query_image_text
8
 
9
  TEST_IAMGE_NAME = "0ddffe51-3763-48d9-ab74-2086de529217"
10
  TEST_UUID = "TEST_UUID"
11
+ test_setting = ReqModel(
12
+ data={
13
+ "token": "test-token",
14
+ "uuid": TEST_UUID,
15
+ "openai_key": "",
16
+ "pinecone_key": "",
17
+ "pinecone_env": "",
18
+ "firebase_key": "",
19
+ "settings": {"temperature": 0.6},
20
+ }
21
+ )
22
+
23
+ firebase_app = initialize_app(test_setting)
24
 
25
 
26
  def test_langchain():
27
  error = "Error happened while analyzing your prompt. Please ask me again"
28
+ result = getCompletion(
29
+ query="open three.js website", setting=test_setting, firebase_app=firebase_app
30
+ )
31
  print(result)
32
  assert result != error
33
 
34
 
35
  def test_image2text():
36
  error = "Error happened while analyzing your prompt. Please ask me again"
37
+ result = getTextFromImage(filename=TEST_IAMGE_NAME, firebase_app=firebase_app)
38
  print(result)
39
  assert result != error
40
 
41
 
42
  def test_firebase_cloud_message():
43
+ cloud_message = CloudMessage(firebase_app=firebase_app)
44
+ token_list = cloud_message.get_tokens()
45
  notification = {"title": "alert", "content": "test"}
46
 
47
  pattern = r"send to \d+ devices, with \d+ successed, with \d+ failed."
48
 
49
+ state, value = cloud_message.send_message(notification, token_list)
50
  assert re.match(pattern, value)
51
 
52
 
53
  def test_query_image_text():
54
  error = "Error happened in querying image & text"
55
+ result = query_image_text(
56
+ image_content=getTextFromImage(
57
+ filename=TEST_IAMGE_NAME, firebase_app=firebase_app
58
+ ),
59
+ message="",
60
+ setting=test_setting,
61
+ )
62
  print(result)
63
  assert result != error
app.py CHANGED
@@ -6,8 +6,6 @@ import uvicorn
6
  from Brain.src.router.browser_router import construct_blueprint_browser_api
7
  from Brain.src.router.train_router import construct_blueprint_train_api
8
 
9
- initialize_app()
10
-
11
  from Brain.src.router.api import construct_blueprint_api
12
 
13
  app = FastAPI()
@@ -26,9 +24,7 @@ app.include_router(
26
  construct_blueprint_browser_api(), prefix="/browser", tags=["ai_browser"]
27
  )
28
 
29
- app.include_router(
30
- construct_blueprint_train_api(), prefix="/train", tags=["ai_train"]
31
- )
32
 
33
 
34
  if __name__ == "__main__":
 
6
  from Brain.src.router.browser_router import construct_blueprint_browser_api
7
  from Brain.src.router.train_router import construct_blueprint_train_api
8
 
 
 
9
  from Brain.src.router.api import construct_blueprint_api
10
 
11
  app = FastAPI()
 
24
  construct_blueprint_browser_api(), prefix="/browser", tags=["ai_browser"]
25
  )
26
 
27
+ app.include_router(construct_blueprint_train_api(), prefix="/train", tags=["ai_train"])
 
 
28
 
29
 
30
  if __name__ == "__main__":