Kotta commited on
Commit ·
74f1630
1
Parent(s): a27c5a5
feature(#9): updated sendNotificaiton with its configuration.
Browse filesFiles changed (9)
- Brain/src/common/assembler.py+12-1
- Brain/src/common/utils.py+2-1
- Brain/src/model/req_model.pyAdded+51
- Brain/src/model/requests/request_model.py+47-3
- Brain/src/rising_plugin/guardrails-config/actions/actions.py+34-15
- Brain/src/rising_plugin/llm/gpt_llm.py+4-3
- Brain/src/rising_plugin/llm/llms.py+15-5
- Brain/src/rising_plugin/risingplugin.py+35-13
- Brain/src/router/api.py+6-2
4 unmodified lines56789101146 unmodified lines5859604 unmodified linesfrom Brain.src.model.basic_model import BasicModelfrom Brain.src.model.contact_model import ContactModelfrom Brain.src.model.message_model import MessageModelfrom Brain.src.model.requests.request_model import ChatRising, SendSMS, TrainContactsfrom Brain.src.model.sms_model import SMSModel46 unmodified linesdef to_result_format(self, program: str, content: str) -> Any:return {"program": program, "content": content}4 unmodified lines56789101112131415161746 unmodified lines64656667686970714 unmodified linesfrom Brain.src.model.basic_model import BasicModelfrom Brain.src.model.contact_model import ContactModelfrom Brain.src.model.message_model import MessageModelfrom Brain.src.model.req_model import ReqModelfrom Brain.src.model.requests.request_model import (ChatRising,SendSMS,TrainContacts,BasicReq,)from Brain.src.model.sms_model import SMSModel46 unmodified linesdef to_result_format(self, program: str, content: str) -> Any:return {"program": program, "content": content}"""mapping basic req"""def to_req_model(self, basic_req: BasicReq) -> ReqModel:return ReqModel(basic_req.to_json())
4 unmodified lines56789106 unmodified lines171819202122234 unmodified linesfrom firebase_admin import credentials# env variablesOPENAI_API_KEY = os.getenv("OPENAI_API_KEY")PINECONE_KEY = os.getenv("PINECONE_KEY")PINECONE_ENV = os.getenv("PINECONE_ENV")6 unmodified lines# firebaseFIREBASE_STORAGE_ROOT = "images/"FIREBASE_STORAGE_BUCKET = "test3-83ffc.appspot.com"# pineconePINECONE_NAMESPACE = "risinglangchain-namespace"4 unmodified lines5678910116 unmodified lines181920212223244 unmodified linesfrom firebase_admin import credentials# env variablesDEFAULT_HOST_NAME = "test3-83ffc.appspot.com"OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")PINECONE_KEY = os.getenv("PINECONE_KEY")PINECONE_ENV = os.getenv("PINECONE_ENV")6 unmodified lines# firebaseFIREBASE_STORAGE_ROOT = "images/"FIREBASE_STORAGE_BUCKET = DEFAULT_HOST_NAME# pineconePINECONE_NAMESPACE = "risinglangchain-namespace"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051from typing import Any
from Brain.src.common.utils import DEFAULT_HOST_NAME
class ReqModel: class Settings: def __init__(self): self.temperature: float = 0.6
host_name: str openai_key: str pinecone_key: str pinecone_env: str firebase_key: str token: str = "" uuid: str = "" settings: Settings
def __init__(self, data: dict): self.host_name = ( DEFAULT_HOST_NAME if data["host_name"] == "" else data["host_name"] ) self.openai_key = ( DEFAULT_HOST_NAME if data["openai_key"] == "" else data["openai_key"] ) self.pinecone_key = ( DEFAULT_HOST_NAME if data["pinecone_key"] == "" else data["pinecone_key"] ) self.pinecone_env = ( DEFAULT_HOST_NAME if data["pinecone_env"] == "" else data["pinecone_env"] ) self.firebase_key = ( DEFAULT_HOST_NAME if data["firebase_key"] == "" else data["firebase_key"] ) self.token = data["token"] self.uuid = data["uuid"] self.settings = self.Settings() self.settings.temperature = data["settings"]["temperature"]
def to_json(self): return { "host_name": self.host_name, "openai_key": self.openai_key, "pinecone_key": self.pinecone_key, "pinecone_env": self.pinecone_env, "firebase_key": self.firebase_key, "settings": {"temperature": self.settings.temperature}, "token": self.token, "uuid": self.uuid, }3 unmodified lines45678940 unmodified lines505152535455565758593 unmodified linesfrom fastapi import Depends, Request, HTTPExceptionfrom user_agents import parse"""user-agent management"""40 unmodified linesreturn parse_user_agent(user_agent)class BasicReq(BaseModel):token: struuid: strmodel: str = "gpt-3.5-turbo""""endpoint: /sendNotification"""3 unmodified lines456789101112131415161740 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021033 unmodified linesfrom fastapi import Depends, Request, HTTPExceptionfrom user_agents import parsefrom Brain.src.common.utils import (DEFAULT_HOST_NAME,OPENAI_API_KEY,PINECONE_KEY,FIREBASE_ENV,PINECONE_ENV,)"""user-agent management"""40 unmodified linesreturn parse_user_agent(user_agent)"""{"host_name": string,"openai_key": string,"pinecone_key": string,"pinecone_env": string,"firebase_key": string,"settings": {"temperature": float},"token": string,"uuid": string,}"""class BasicReq(BaseModel):class Settings(BaseModel):temperature: float = 0.6host_name: stropenai_key: strpinecone_key: strpinecone_env: strfirebase_key: strtoken: str = ""uuid: str = ""settings: Settingsdef to_json(self):return {"host_name": self.host_name,"openai_key": self.openai_key,"pinecone_key": self.pinecone_key,"pinecone_env": self.pinecone_env,"firebase_key": self.firebase_key,"settings": {"temperature": self.settings.temperature},"token": self.token,"uuid": self.uuid,}"""endpoint: /sendNotification"""
26 unmodified lines272829303132338 unmodified lines4243444546473 unmodified lines5152535455565758596061624 unmodified lines676869707172737475767778799 unmodified lines89909192939495969798991001011021032 unmodified lines1061071081091101111121131141151161171 unmodified line11912012112226 unmodified linesOPENAI_API_KEY,COMMAND_SMS_INDEXS,COMMAND_BROWSER_OPEN,)from Brain.src.rising_plugin.image_embedding import (query_image_text,)8 unmodified linesGPT_4_32K,GPT_4,FALCON_7B,)"""3 unmodified lines"model": string,"uuid": string,"image_search": bool,}"""@action()async def general_question(query):"""step 0: convert string to json"""try:json_query = json.loads(query)4 unmodified linesmodel = json_query["model"]uuid = json_query["uuid"]image_search = json_query["image_search"]"""step 1: handle with gpt-4"""file_path = os.path.dirname(os.path.abspath(__file__))with open(f"{file_path}/phone.json", "r") as infile:data = json.load(infile)embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY)query_result = embeddings.embed_query(query)doc_list = utils.maximal_marginal_relevance(np.array(query_result), data, k=1)9 unmodified lines))chain_data = get_llm_chain(model=model).run(input_documents=docs, question=query)# test# if model == GPT_3_5_TURBO or model == GPT_4 or model == GPT_4_32K:# gpt_llm = GptLLM(model=model)# chain_data = gpt_llm.get_chain().run(input_documents=docs, question=query)# elif model == FALCON_7B:# falcon_llm = FalconLLM()# chain_data = falcon_llm.get_chain().run(question=query)falcon_llm = FalconLLM()try:result = json.loads(chain_data)# check image query with only its text2 unmodified linesresult["content"] = {"image_name": query_image_text(result["content"], "", uuid)}# else:# return result"""check program is message to handle it with falcon llm"""if result["program"] == "message":result["content"] = falcon_llm.query(question=query)return str(result)except ValueError as e:# Check sms and browser query1 unmodified linereturn str({"program": "sms", "content": chain_data})elif doc_list[0] in COMMAND_BROWSER_OPEN:return str({"program": "browser", "content": "https://google.com"})return str({"program": "message", "content": falcon_llm.query(question=query)})26 unmodified lines272829303132333435368 unmodified lines454647484950513 unmodified lines5556575859606162636465666768697071727374757677787980814 unmodified lines86878889909192939495969798999 unmodified lines1091101111121131141151161171181191201211221232 unmodified lines1261271281291301311321331341351 unmodified line13713813914014126 unmodified linesOPENAI_API_KEY,COMMAND_SMS_INDEXS,COMMAND_BROWSER_OPEN,DEFAULT_GPT_MODEL,)from Brain.src.model.req_model import ReqModelfrom Brain.src.model.requests.request_model import BasicReqfrom Brain.src.rising_plugin.image_embedding import (query_image_text,)8 unmodified linesGPT_4_32K,GPT_4,FALCON_7B,GPT_LLM_MODELS,)"""3 unmodified lines"model": string,"uuid": string,"image_search": bool,"setting": {"host_name": string,"openai_key": string,"pinecone_key": string,"pinecone_env": string,"firebase_key": string,"firebase_env": string"settings": {"temperature": float},"token": string,"uuid": string,}}"""@action()async def general_question(query):"""init falcon model"""falcon_llm = FalconLLM()"""step 0: convert string to json"""try:json_query = json.loads(query)4 unmodified linesmodel = json_query["model"]uuid = json_query["uuid"]image_search = json_query["image_search"]setting = ReqModel(json_query["setting"])"""step 1: handle with gpt-4"""file_path = os.path.dirname(os.path.abspath(__file__))with open(f"{file_path}/phone.json", "r") as infile:data = json.load(infile)embeddings = OpenAIEmbeddings(openai_api_key=setting.openai_key)query_result = embeddings.embed_query(query)doc_list = utils.maximal_marginal_relevance(np.array(query_result), data, k=1)9 unmodified lines))""" 1. calling gpt model to categorize for all message"""if model in GPT_LLM_MODELS:chain_data = get_llm_chain(model=model, setting=setting).run(input_documents=docs, question=query)else:chain_data = get_llm_chain(model=DEFAULT_GPT_MODEL, setting=setting).run(input_documents=docs, question=query)try:result = json.loads(chain_data)# check image query with only its text2 unmodified linesresult["content"] = {"image_name": query_image_text(result["content"], "", uuid)}""" 2. check program is message to handle it with falcon llm """if result["program"] == "message":if model == FALCON_7B:result["content"] = falcon_llm.query(question=query)return str(result)except ValueError as e:# Check sms and browser query1 unmodified linereturn str({"program": "sms", "content": chain_data})elif doc_list[0] in COMMAND_BROWSER_OPEN:return str({"program": "browser", "content": "https://google.com"})return str({"program": "message", "content": falcon_llm.query(question=query)})
8 unmodified lines910111213141516171819208 unmodified linesclass GptLLM:def __init__(self, model: str = "gpt-3.5-turbo", temperature: float = 0.6):self.llm = self.init_llm(model=model, temperature=temperature)def init_llm(self, model: str = "gpt-3.5-turbo", temperature: float = 0.6) -> Any:self.llm = ChatOpenAI(model_name=model, temperature=temperature, openai_api_key=OPENAI_API_KEY)return self.llm8 unmodified lines91011121314151617181920218 unmodified linesclass GptLLM:def __init__(self, openai_key: str, model: str = "gpt-4", temperature: float = 0.6):self.key = openai_keyself.llm = self.init_llm(model=model, temperature=temperature)def init_llm(self, model: str = "gpt-4", temperature: float = 0.6) -> Any:self.llm = ChatOpenAI(model_name=model, temperature=temperature, openai_api_key=self.key)return self.llm
1 unmodified line2345674 unmodified lines12131415161717 unmodified lines35363738394041424344454647484950515253545556571 unmodified linefrom typing import Anyfrom Brain.src.common.brain_exception import BrainExceptionfrom Brain.src.rising_plugin.llm.falcon_llm import FalconLLMfrom Brain.src.rising_plugin.llm.gpt_llm import GptLLM4 unmodified lines"""list of available model we offer you"""LLM_MODELS = [GPT_3_5_TURBO, GPT_4, GPT_4_32K, FALCON_7B]"""exception message"""17 unmodified linesdef get_llm_chain(model: str, temperature: float = 0.6, max_new_tokens: int = 2000) -> Any:if not validate_model(model):raise BrainException(EXCEPTION_MSG)"""check model"""llm = get_llm(model=model, temperature=temperature, max_new_tokens=max_new_tokens)return llm.get_chain()def get_llm(model: str, temperature: float = 0.6, max_new_tokens: int = 2000) -> Any:if not validate_model(model):raise BrainException(EXCEPTION_MSG)"""check model"""llm = GptLLM()if model == GPT_3_5_TURBO or model == GPT_4 or model == GPT_4_32K:llm = GptLLM(model=model)elif model == FALCON_7B:llm = FalconLLM(temperature=temperature, max_new_tokens=max_new_tokens)return llm1 unmodified line234567894 unmodified lines1415161718192017 unmodified lines3839404142434445464748495051525354555657585960616263646566671 unmodified linefrom typing import Anyfrom Brain.src.common.brain_exception import BrainExceptionfrom Brain.src.model.req_model import ReqModelfrom Brain.src.model.requests.request_model import BasicReqfrom Brain.src.rising_plugin.llm.falcon_llm import FalconLLMfrom Brain.src.rising_plugin.llm.gpt_llm import GptLLM4 unmodified lines"""list of available model we offer you"""LLM_MODELS = [GPT_3_5_TURBO, GPT_4, GPT_4_32K, FALCON_7B]GPT_LLM_MODELS = [GPT_3_5_TURBO, GPT_4, GPT_4_32K]"""exception message"""17 unmodified linesdef get_llm_chain(setting: ReqModel, model: str, temperature: float = 0.6, max_new_tokens: int = 2000) -> Any:if not validate_model(model):raise BrainException(EXCEPTION_MSG)"""check model"""llm = get_llm(model=model,temperature=temperature,max_new_tokens=max_new_tokens,setting=setting,)return llm.get_chain()def get_llm(setting: ReqModel, model: str, temperature: float = 0.6, max_new_tokens: int = 2000) -> Any:if not validate_model(model):raise BrainException(EXCEPTION_MSG)"""check model"""llm = GptLLM(openai_key=setting.openai_key)if model == GPT_3_5_TURBO or model == GPT_4 or model == GPT_4_32K:llm = GptLLM(model=model, openai_key=setting.openai_key)elif model == FALCON_7B:llm = FalconLLM(temperature=temperature, max_new_tokens=max_new_tokens)return llm
24 unmodified lines25262728293010 unmodified lines414243444546471 unmodified line49505152535434 unmodified lines89909192939421 unmodified lines1161171181191201218 unmodified lines1301311321331341351361371381391401411421431441451461471487 unmodified lines15615715815916016116216316416548 unmodified lines21421521621721821922022122222322422522622722811 unmodified lines24024124224324424524624724824925025125224 unmodified linesquery_image_text,get_prompt_image_with_message,)# Give the path to the folder containing the railsfile_path = os.path.dirname(os.path.abspath(__file__))10 unmodified linesdef processLargeText(app: any, chunks: any, model: str, uuid: str = "", image_search: bool = True):if len(chunks) == 1:message = app.generate(1 unmodified line{"role": "user","content": rails_input_with_args(query=chunks[0],model=model,uuid=uuid,34 unmodified lines{"role": "user","content": rails_input_with_args(query=chunk_query,model=model,uuid=uuid,21 unmodified lines{"role": "user","content": rails_input_with_args(query=last_query,model=model,uuid=uuid,8 unmodified linesdef getCompletion(query,model=DEFAULT_GPT_MODEL,uuid="",image_search=True,):llm = get_llm(model=DEFAULT_GPT_MODEL).get_llm()# Break input text into chunkschunks = getChunks(query)app = LLMRails(config, llm)return processLargeText(app=app, chunks=chunks, model=model, uuid=uuid, image_search=image_search)7 unmodified linesreturn chain_datadef query_image_ask(image_content, message, uuid):prompt_template = get_prompt_image_with_message(image_content, message)try:data = getCompletion(query=prompt_template, uuid=uuid, image_search=False)# chain_data = json.loads(data.replace("'", '"'))# chain_data = json.loads(data)if data["program"] == "image":48 unmodified lines# Define a content filter functiondef filter_guardrails(model: any, query: str):llm = ChatOpenAI(model_name=model, temperature=0, openai_api_key=OPENAI_API_KEY)app = LLMRails(config, llm)# split query with chunkschunks = getChunks(query)# get message from guardrailsmessage = processLargeText(app=app, chunks=chunks, model=model)if (message11 unmodified lines"""def rails_input_with_args(query: str, model: str, uuid: str, image_search: bool) -> str:# convert json with params for rails.json_query_with_params = {"query": query,"model": model,"uuid": uuid,"image_search": image_search,}return json.dumps(json_query_with_params)24 unmodified lines252627282930313210 unmodified lines4344454647484950515253541 unmodified line5657585960616234 unmodified lines97989910010110210321 unmodified lines1251261271281291301318 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641657 unmodified lines17317417517617717817918018118218318448 unmodified lines23323423523623723823924024124224324424524624711 unmodified lines25926026126226326426526626726826927027127227327424 unmodified linesquery_image_text,get_prompt_image_with_message,)from ..model.req_model import ReqModelfrom ..model.requests.request_model import BasicReq# Give the path to the folder containing the railsfile_path = os.path.dirname(os.path.abspath(__file__))10 unmodified linesdef processLargeText(setting: ReqModel,app: any,chunks: any,model: str,uuid: str = "",image_search: bool = True,):if len(chunks) == 1:message = app.generate(1 unmodified line{"role": "user","content": rails_input_with_args(setting=setting,query=chunks[0],model=model,uuid=uuid,34 unmodified lines{"role": "user","content": rails_input_with_args(setting=setting,query=chunk_query,model=model,uuid=uuid,21 unmodified lines{"role": "user","content": rails_input_with_args(setting=setting,query=last_query,model=model,uuid=uuid,8 unmodified linesdef getCompletion(query: str,setting: ReqModel,model: str = DEFAULT_GPT_MODEL,uuid: str = "",image_search: bool = True,):llm = get_llm(model=DEFAULT_GPT_MODEL, setting=setting).get_llm()# Break input text into chunkschunks = getChunks(query)app = LLMRails(config, llm)return processLargeText(setting=setting,app=app,chunks=chunks,model=model,uuid=uuid,image_search=image_search,)7 unmodified linesreturn chain_datadef query_image_ask(image_content, message, uuid, setting: BasicReq):prompt_template = get_prompt_image_with_message(image_content, message)try:data = getCompletion(query=prompt_template, uuid=uuid, image_search=False, setting=setting)# chain_data = json.loads(data.replace("'", '"'))# chain_data = json.loads(data)if data["program"] == "image":48 unmodified lines# Define a content filter functiondef filter_guardrails(setting: BasicReq, model: any, query: str):llm = ChatOpenAI(model_name=model, temperature=0, openai_api_key=setting.openai_key)app = LLMRails(config, llm)# split query with chunkschunks = getChunks(query)# get message from guardrailsmessage = processLargeText(app=app, chunks=chunks, model=model, setting=setting)if (message11 unmodified lines"""def rails_input_with_args(setting: ReqModel, query: str, model: str, uuid: str, image_search: bool) -> str:# convert json with params for rails.json_query_with_params = {"query": query,"model": model,"uuid": uuid,"image_search": image_search,"setting": setting.to_json(),}return json.dumps(json_query_with_params)
67 unmodified lines6869707172737469 unmodified lines14414514614714814915067 unmodified linesif client_info.is_browser():query = f"{query} in a web browser"result = getCompletion(query=query, uuid=uuid)# check contact queryingtry:69 unmodified linesimage_response = {}try:# check about asking image description with trained dataif query_image_ask(image_content, message, uuid):image_response["image_desc"] = image_contentelse:relatedness_data = query_image_text(image_content, message, uuid)67 unmodified lines68697071727374757669 unmodified lines14614714814915015115215315467 unmodified linesif client_info.is_browser():query = f"{query} in a web browser"result = getCompletion(query=query, uuid=uuid, setting=assembler.to_req_model(data))# check contact queryingtry:69 unmodified linesimage_response = {}try:# check about asking image description with trained dataif query_image_ask(image_content=image_content, message=message, uuid=uuid, setting=data):image_response["image_desc"] = image_contentelse:relatedness_data = query_image_text(image_content, message, uuid)
Brain/src/common/assembler.py+12-1
Brain/src/common/utils.py+2-1
Brain/src/model/req_model.pyAdded+51
Brain/src/model/requests/request_model.py+47-3
Brain/src/rising_plugin/guardrails-config/actions/actions.py+34-15
Brain/src/rising_plugin/llm/gpt_llm.py+4-3
Brain/src/rising_plugin/llm/llms.py+15-5
Brain/src/rising_plugin/risingplugin.py+35-13
Brain/src/router/api.py+6-2