Dev step
Browse files- main.py +29 -14
- modules/llm.py +12 -9
- modules/model.py +16 -4
- static/js/chatHandler.js +4 -1
main.py
CHANGED
|
@@ -73,52 +73,67 @@ async def validate_oauth(request: Request):
|
|
| 73 |
|
| 74 |
# Saves the user
|
| 75 |
user.update_user()
|
| 76 |
-
|
| 77 |
-
|
| 78 |
return response
|
|
|
|
| 79 |
##########################################################
|
| 80 |
|
| 81 |
|
| 82 |
-
######################
|
| 83 |
|
|
|
|
| 84 |
User_find_from_data = Annotated[User, Depends(User.find_from_data)]
|
| 85 |
Session_find_from_data = Annotated[Session, Depends(Session.find_from_data)]
|
| 86 |
|
| 87 |
@app.post("/getConfigs")
|
| 88 |
async def get_configs(response: Response, user: User_find_from_data):
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
| 91 |
total = sum([z for x in user.tokens.values() for y in x.values() for z in y.values()])
|
| 92 |
tokens = {"month": month, "total": total}
|
|
|
|
|
|
|
| 93 |
user._session.create_cookie(response)
|
| 94 |
return user.configs.model_dump() | {"tokens": tokens, "challenge": user._session.challenge}
|
| 95 |
|
| 96 |
@app.post("/setConfigs")
|
| 97 |
async def set_configs(response: Response, user: User_find_from_data):
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
user.update_user()
|
|
|
|
|
|
|
| 100 |
user._session.create_cookie(response)
|
| 101 |
return {"success":True, "challenge": user._session.challenge}
|
| 102 |
|
| 103 |
-
|
| 104 |
@app.post("/getToken")
|
| 105 |
async def get_token(response: Response, session: Session_find_from_data):
|
|
|
|
| 106 |
session.create_cookie(response)
|
|
|
|
|
|
|
| 107 |
return {"success":True, "challenge": session.challenge}
|
| 108 |
|
|
|
|
| 109 |
|
| 110 |
@app.post("/chat")
|
| 111 |
-
async def chat_async(
|
|
|
|
| 112 |
if(len(body.messages) < 1 or body.messages[-1].content==""):
|
| 113 |
-
log_module.logger.warning(
|
| 114 |
raise HTTPException(
|
| 115 |
status_code=status.HTTP_418_IM_A_TEAPOT,
|
| 116 |
detail= "Nope"
|
| 117 |
)
|
| 118 |
|
| 119 |
-
response_async = llm.ejecutar(body,
|
| 120 |
-
|
| 121 |
-
return StreamingResponse(llm.streamer(response_async, body,
|
| 122 |
|
| 123 |
|
| 124 |
########################## Static Pages ##########################
|
|
@@ -126,7 +141,7 @@ async def chat_async(request: Request, body: model.Chat, user ): # = Depends(mod
|
|
| 126 |
async def privacy_policy(request: Request):
|
| 127 |
return templates.TemplateResponse("PrivacyPolicy.html", {"request": request})
|
| 128 |
|
| 129 |
-
@app.get("/hold")
|
| 130 |
async def on_hold(request: Request, user: User = Depends(User.find_from_cookie)):
|
| 131 |
redirect_to_login = RedirectResponse(url='/login')
|
| 132 |
|
|
@@ -139,7 +154,7 @@ async def on_hold(request: Request, user: User = Depends(User.find_from_cookie))
|
|
| 139 |
"description": bool(user.description)
|
| 140 |
})
|
| 141 |
|
| 142 |
-
@app.post("/hold")
|
| 143 |
async def on_hold(request: Request, user: User = Depends(User.find_from_cookie)):
|
| 144 |
if not user.description:
|
| 145 |
form = await request.form()
|
|
|
|
| 73 |
|
| 74 |
# Saves the user
|
| 75 |
user.update_user()
|
|
|
|
|
|
|
| 76 |
return response
|
| 77 |
+
|
| 78 |
##########################################################
|
| 79 |
|
| 80 |
|
| 81 |
+
###################### APIs Configs ######################
|
| 82 |
|
| 83 |
+
# Get data and structures from its models
|
| 84 |
User_find_from_data = Annotated[User, Depends(User.find_from_data)]
|
| 85 |
Session_find_from_data = Annotated[Session, Depends(Session.find_from_data)]
|
| 86 |
|
| 87 |
@app.post("/getConfigs")
|
| 88 |
async def get_configs(response: Response, user: User_find_from_data):
|
| 89 |
+
# Get config from DB to client
|
| 90 |
+
|
| 91 |
+
# Get llm tokens used
|
| 92 |
+
year_, month_ = datetime.now().strftime("%y-%m").split("-")
|
| 93 |
+
month = sum(user.tokens.get(year_, {}).get(month_, {"_":0}).values())
|
| 94 |
total = sum([z for x in user.tokens.values() for y in x.values() for z in y.values()])
|
| 95 |
tokens = {"month": month, "total": total}
|
| 96 |
+
|
| 97 |
+
# Create cookies and answer
|
| 98 |
user._session.create_cookie(response)
|
| 99 |
return user.configs.model_dump() | {"tokens": tokens, "challenge": user._session.challenge}
|
| 100 |
|
| 101 |
@app.post("/setConfigs")
|
| 102 |
async def set_configs(response: Response, user: User_find_from_data):
|
| 103 |
+
# Save configs from users to DB
|
| 104 |
+
|
| 105 |
+
# Create config model
|
| 106 |
+
user.configs = model.Configs(**user._data)
|
| 107 |
+
user._session.configs = user.configs
|
| 108 |
user.update_user()
|
| 109 |
+
|
| 110 |
+
# Create cookies and answer
|
| 111 |
user._session.create_cookie(response)
|
| 112 |
return {"success":True, "challenge": user._session.challenge}
|
| 113 |
|
|
|
|
| 114 |
@app.post("/getToken")
|
| 115 |
async def get_token(response: Response, session: Session_find_from_data):
|
| 116 |
+
# Generate api token
|
| 117 |
session.create_cookie(response)
|
| 118 |
+
|
| 119 |
+
# Create cookies and answer
|
| 120 |
return {"success":True, "challenge": session.challenge}
|
| 121 |
|
| 122 |
+
##########################################################
|
| 123 |
|
| 124 |
@app.post("/chat")
|
| 125 |
+
async def chat_async(response:Response, session: Session_find_from_data):
|
| 126 |
+
body = model.Chat(messages = session.data["messages"])
|
| 127 |
if(len(body.messages) < 1 or body.messages[-1].content==""):
|
| 128 |
+
log_module.logger.warning(session.gid, "Mensaje RQ", "error, mensajes vacios")
|
| 129 |
raise HTTPException(
|
| 130 |
status_code=status.HTTP_418_IM_A_TEAPOT,
|
| 131 |
detail= "Nope"
|
| 132 |
)
|
| 133 |
|
| 134 |
+
response_async = llm.ejecutar(body, session)
|
| 135 |
+
session.create_cookie(response)
|
| 136 |
+
return StreamingResponse(llm.streamer(response_async, body, session), media_type="application/json")
|
| 137 |
|
| 138 |
|
| 139 |
########################## Static Pages ##########################
|
|
|
|
| 141 |
async def privacy_policy(request: Request):
|
| 142 |
return templates.TemplateResponse("PrivacyPolicy.html", {"request": request})
|
| 143 |
|
| 144 |
+
@app.get("/hold")
|
| 145 |
async def on_hold(request: Request, user: User = Depends(User.find_from_cookie)):
|
| 146 |
redirect_to_login = RedirectResponse(url='/login')
|
| 147 |
|
|
|
|
| 154 |
"description": bool(user.description)
|
| 155 |
})
|
| 156 |
|
| 157 |
+
@app.post("/hold")
|
| 158 |
async def on_hold(request: Request, user: User = Depends(User.find_from_cookie)):
|
| 159 |
if not user.description:
|
| 160 |
form = await request.form()
|
modules/llm.py
CHANGED
|
@@ -18,7 +18,7 @@ if TYPE_CHECKING:
|
|
| 18 |
encoding = tiktoken.encoding_for_model(settings.GPT_MODEL)
|
| 19 |
|
| 20 |
|
| 21 |
-
def ejecutar(body: "model.
|
| 22 |
temp_messages = [{"role":msg.role, "content":msg.content} for msg in body.messages]
|
| 23 |
|
| 24 |
try:
|
|
@@ -30,16 +30,17 @@ def ejecutar(body: "model.Body", user: "model.User"):
|
|
| 30 |
generated = client.chat.completions.create(
|
| 31 |
model=settings.GPT_MODEL,
|
| 32 |
messages=temp_messages,
|
| 33 |
-
temperature=
|
| 34 |
-
frequency_penalty=
|
| 35 |
-
presence_penalty=
|
| 36 |
-
tools= tools.functions if
|
| 37 |
stream=True,
|
| 38 |
-
user=sha256(
|
| 39 |
)
|
|
|
|
| 40 |
return generated
|
| 41 |
except Exception as error:
|
| 42 |
-
log_module.logger.error(repr(error) + " - " +
|
| 43 |
raise HTTPException( **error_map.error_table.get(type(error), error_map.error_table["undefined"]))
|
| 44 |
|
| 45 |
def manejar_funciones(chunk, response_async, data):
|
|
@@ -60,7 +61,7 @@ def manejar_funciones(chunk, response_async, data):
|
|
| 60 |
})
|
| 61 |
return json.dumps(f_cb), ejecutar(data)
|
| 62 |
|
| 63 |
-
async def streamer(response_async, body,
|
| 64 |
yield json.dumps({"comando": "status", "status":{"mensaje":"Cargando", "modo": "reemplazar"}})
|
| 65 |
message = body.new_msg()
|
| 66 |
|
|
@@ -91,5 +92,7 @@ async def streamer(response_async, body, user):
|
|
| 91 |
st_times += 1
|
| 92 |
st = time.time()
|
| 93 |
message.tokensPrompt = body.tokens
|
| 94 |
-
|
|
|
|
|
|
|
| 95 |
yield json.dumps({"comando":"mensaje", "mensaje": message.model_dump()} )
|
|
|
|
| 18 |
encoding = tiktoken.encoding_for_model(settings.GPT_MODEL)
|
| 19 |
|
| 20 |
|
| 21 |
+
def ejecutar(body: "model.Chat", session: "model.Session"):
|
| 22 |
temp_messages = [{"role":msg.role, "content":msg.content} for msg in body.messages]
|
| 23 |
|
| 24 |
try:
|
|
|
|
| 30 |
generated = client.chat.completions.create(
|
| 31 |
model=settings.GPT_MODEL,
|
| 32 |
messages=temp_messages,
|
| 33 |
+
temperature=session.configs.temperature,
|
| 34 |
+
frequency_penalty=session.configs.frequency_penalty,
|
| 35 |
+
presence_penalty=session.configs.presence_penalty,
|
| 36 |
+
tools= tools.functions if session.configs.useTool else None,
|
| 37 |
stream=True,
|
| 38 |
+
user=sha256(session.gid.encode('UTF-8')).hexdigest()
|
| 39 |
)
|
| 40 |
+
|
| 41 |
return generated
|
| 42 |
except Exception as error:
|
| 43 |
+
log_module.logger.error(repr(error) + " - " + session.gid)
|
| 44 |
raise HTTPException( **error_map.error_table.get(type(error), error_map.error_table["undefined"]))
|
| 45 |
|
| 46 |
def manejar_funciones(chunk, response_async, data):
|
|
|
|
| 61 |
})
|
| 62 |
return json.dumps(f_cb), ejecutar(data)
|
| 63 |
|
| 64 |
+
async def streamer(response_async, body, session):
|
| 65 |
yield json.dumps({"comando": "status", "status":{"mensaje":"Cargando", "modo": "reemplazar"}})
|
| 66 |
message = body.new_msg()
|
| 67 |
|
|
|
|
| 92 |
st_times += 1
|
| 93 |
st = time.time()
|
| 94 |
message.tokensPrompt = body.tokens
|
| 95 |
+
session.update_usage(message)
|
| 96 |
+
|
| 97 |
+
yield json.dumps({"comando":"challenge", "challenge": session.challenge} )
|
| 98 |
yield json.dumps({"comando":"mensaje", "mensaje": message.model_dump()} )
|
modules/model.py
CHANGED
|
@@ -68,6 +68,7 @@ class Session(BaseModel):
|
|
| 68 |
public_key: str = ""
|
| 69 |
challenge: str = str(uuid.uuid4())
|
| 70 |
data: dict = {}
|
|
|
|
| 71 |
|
| 72 |
def __init__(self, **kwargs):
|
| 73 |
kwargs["guid"] = kwargs.get("guid", str(uuid.uuid4()))
|
|
@@ -104,7 +105,8 @@ class Session(BaseModel):
|
|
| 104 |
fprint = data["fingerprint"],
|
| 105 |
guid = cookie_data["guid"],
|
| 106 |
public_key = public_key,
|
| 107 |
-
data = data
|
|
|
|
| 108 |
)
|
| 109 |
|
| 110 |
if session.hashed != cookie_data["fprint"]:
|
|
@@ -122,9 +124,13 @@ class Session(BaseModel):
|
|
| 122 |
"guid": self.guid,
|
| 123 |
"fprint": self.hashed,
|
| 124 |
"public_key": self.public_key,
|
| 125 |
-
"challenge": self.challenge
|
|
|
|
| 126 |
})
|
| 127 |
security.set_cookie(response, "token", jwt, {"hours": 24})
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
class User(BaseModel):
|
| 130 |
name: str
|
|
@@ -173,8 +179,11 @@ class User(BaseModel):
|
|
| 173 |
user._session = Session(
|
| 174 |
gid = cookie_data["gid"],
|
| 175 |
guid = cookie_data["guid"],
|
| 176 |
-
fprint = cookie_data["fprint"]
|
|
|
|
| 177 |
)
|
|
|
|
|
|
|
| 178 |
return user
|
| 179 |
|
| 180 |
@classmethod
|
|
@@ -189,6 +198,7 @@ class User(BaseModel):
|
|
| 189 |
|
| 190 |
user: Self = cls(**found)
|
| 191 |
user._session = session
|
|
|
|
| 192 |
return user
|
| 193 |
|
| 194 |
def update_description(self: Self, message: str) -> None:
|
|
@@ -216,7 +226,9 @@ class User(BaseModel):
|
|
| 216 |
return security.create_jwt_token({
|
| 217 |
"gid":self.gid,
|
| 218 |
"guid": self._session.guid,
|
| 219 |
-
"fprint": self._session.hashed
|
|
|
|
|
|
|
| 220 |
|
| 221 |
|
| 222 |
|
|
|
|
| 68 |
public_key: str = ""
|
| 69 |
challenge: str = str(uuid.uuid4())
|
| 70 |
data: dict = {}
|
| 71 |
+
configs: Configs | None = None
|
| 72 |
|
| 73 |
def __init__(self, **kwargs):
|
| 74 |
kwargs["guid"] = kwargs.get("guid", str(uuid.uuid4()))
|
|
|
|
| 105 |
fprint = data["fingerprint"],
|
| 106 |
guid = cookie_data["guid"],
|
| 107 |
public_key = public_key,
|
| 108 |
+
data = data,
|
| 109 |
+
configs = Configs(**cookie_data["configs"])
|
| 110 |
)
|
| 111 |
|
| 112 |
if session.hashed != cookie_data["fprint"]:
|
|
|
|
| 124 |
"guid": self.guid,
|
| 125 |
"fprint": self.hashed,
|
| 126 |
"public_key": self.public_key,
|
| 127 |
+
"challenge": self.challenge,
|
| 128 |
+
"configs": self.configs.model_dump()
|
| 129 |
})
|
| 130 |
security.set_cookie(response, "token", jwt, {"hours": 24})
|
| 131 |
+
|
| 132 |
+
def update_usage(self: Self, message:Message):
|
| 133 |
+
User.update_usage(self.gid, message)
|
| 134 |
|
| 135 |
class User(BaseModel):
|
| 136 |
name: str
|
|
|
|
| 179 |
user._session = Session(
|
| 180 |
gid = cookie_data["gid"],
|
| 181 |
guid = cookie_data["guid"],
|
| 182 |
+
fprint = cookie_data["fprint"],
|
| 183 |
+
configs = user.configs
|
| 184 |
)
|
| 185 |
+
print("configs user", id(user.configs))
|
| 186 |
+
print("configs sesison", id(user._session.configs))
|
| 187 |
return user
|
| 188 |
|
| 189 |
@classmethod
|
|
|
|
| 198 |
|
| 199 |
user: Self = cls(**found)
|
| 200 |
user._session = session
|
| 201 |
+
user._data = data
|
| 202 |
return user
|
| 203 |
|
| 204 |
def update_description(self: Self, message: str) -> None:
|
|
|
|
| 226 |
return security.create_jwt_token({
|
| 227 |
"gid":self.gid,
|
| 228 |
"guid": self._session.guid,
|
| 229 |
+
"fprint": self._session.hashed,
|
| 230 |
+
"configs": self.configs.model_dump()
|
| 231 |
+
})
|
| 232 |
|
| 233 |
|
| 234 |
|
static/js/chatHandler.js
CHANGED
|
@@ -280,7 +280,8 @@ class ChatGPT{
|
|
| 280 |
method: "POST",
|
| 281 |
body: JSON.stringify({
|
| 282 |
messages: tempMensajes,
|
| 283 |
-
|
|
|
|
| 284 |
}),
|
| 285 |
headers: {
|
| 286 |
"Autorization": "Bearer " + this.token,
|
|
@@ -295,6 +296,8 @@ class ChatGPT{
|
|
| 295 |
return
|
| 296 |
}
|
| 297 |
return consume(response.body.getReader());
|
|
|
|
|
|
|
| 298 |
})
|
| 299 |
.catch(err =>{
|
| 300 |
// Error
|
|
|
|
| 280 |
method: "POST",
|
| 281 |
body: JSON.stringify({
|
| 282 |
messages: tempMensajes,
|
| 283 |
+
challenge: this.challenge,
|
| 284 |
+
fingerprint: this.secHand.fingerprint
|
| 285 |
}),
|
| 286 |
headers: {
|
| 287 |
"Autorization": "Bearer " + this.token,
|
|
|
|
| 296 |
return
|
| 297 |
}
|
| 298 |
return consume(response.body.getReader());
|
| 299 |
+
}).then(data => {
|
| 300 |
+
console.log("esto", data)
|
| 301 |
})
|
| 302 |
.catch(err =>{
|
| 303 |
// Error
|