Feat: Adds cognito and memory
This commit is contained in:
BIN
front/app/__pycache__/st_auth.cpython-312.pyc
Normal file
BIN
front/app/__pycache__/st_auth.cpython-312.pyc
Normal file
Binary file not shown.
69
front/app/front.py
Normal file
69
front/app/front.py
Normal file
@@ -0,0 +1,69 @@
|
||||
import streamlit as st
|
||||
from typing import Set
|
||||
import requests
|
||||
import json
|
||||
import yaml
|
||||
import st_auth
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
import jwt
|
||||
headers = st.context.headers
|
||||
|
||||
# The ID token contains user claims
|
||||
id_token = headers.get('x-amzn-oidc-data')
|
||||
decoded = jwt.decode(id_token, options={"verify_signature": False})
|
||||
|
||||
# Tenta diferentes campos onde o user_id pode estar
|
||||
user_id = (
|
||||
decoded.get("sub") or # Subject (padrão JWT)
|
||||
decoded.get("cognito:username") or # Username do Cognito
|
||||
decoded.get("username") or # Username alternativo
|
||||
decoded.get("user_id") # Campo customizado
|
||||
)
|
||||
st.header("Assistente Produtos Servicos")
|
||||
url="https://xexm2wsz07-vpce-05915540d0592b921.execute-api.us-east-1.amazonaws.com/dev"
|
||||
payload=[]
|
||||
message_history=[]
|
||||
if "user_prompt_history" not in st.session_state:
|
||||
st.session_state["user_prompt_history"]=[]
|
||||
if "chat_answer_history" not in st.session_state:
|
||||
st.session_state["chat_answer_history"]=[]
|
||||
if "chat_history" not in st.session_state:
|
||||
st.session_state["chat_history"] = []
|
||||
prompt=st.chat_input(placeholder="Digite uma mensagem...",key="prompt")
|
||||
for generated_response, user_query in zip(st.session_state["chat_answer_history"],st.session_state["user_prompt_history"]):
|
||||
st.chat_message("user").write(user_query)
|
||||
st.chat_message("assistant").write(generated_response)
|
||||
def create_sources_string(source_urls: Set[str])->str:
|
||||
if not source_urls:
|
||||
return ""
|
||||
source_list=list(source_urls)
|
||||
source_list.sort()
|
||||
sources_string="source:\n"
|
||||
for i, source in enumerate(source_list):
|
||||
sources_string+=f"{i+1}, {source}\n"
|
||||
return sources_string
|
||||
if prompt:
|
||||
st.chat_message("user").write(prompt)
|
||||
with st.spinner("Generating response.."):
|
||||
payload=[{"role":"user","content":prompt}]
|
||||
content={"message":payload,"chat_history":st.session_state["chat_history"],"username":user_id}
|
||||
headers={"Content-type":"application/json","x-api-key":json.loads(st_auth.get_secret())['api-gateway-api-key']}
|
||||
generated_response=json.loads(requests.post(url,json=content,headers=headers).text)
|
||||
if 'chat_history' in generated_response:
|
||||
if st.session_state["chat_history"] == []:
|
||||
st.session_state["chat_history"] = generated_response['chat_history']
|
||||
if 'json' in generated_response:
|
||||
generated_response=generated_response['json']
|
||||
if 'message' in generated_response and generated_response['message']=="Endpoint request timed out":
|
||||
generated_response="Falta de dados: Por favor encaminhe a conversa para a equipe desenvolvedora"
|
||||
#generated_response=[{"role":"user","content":prompt}]
|
||||
# sources= set([doc.metadata["source"] for doc in generated_response['context']])
|
||||
#formatted_response=f"{generated_response['answer']} \n\n {create_sources_string(sources)}"
|
||||
formatted_response=generated_response
|
||||
st.chat_message("assistant").write(formatted_response)
|
||||
st.session_state["user_prompt_history"].append(prompt)
|
||||
st.session_state["chat_answer_history"].append(formatted_response)
|
||||
st.session_state["chat_history"]=st.session_state["chat_history"]+[{"role":"user","content":prompt}]+[{"role":"assistant","content":formatted_response}]
|
||||
st.session_state.user_input=""
|
||||
|
||||
102
front/app/st_auth.py
Normal file
102
front/app/st_auth.py
Normal file
@@ -0,0 +1,102 @@
|
||||
import streamlit_authenticator as stauth
|
||||
import yaml
|
||||
from yaml.loader import SafeLoader
|
||||
import streamlit as st
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
def get_authenticator():
|
||||
# with open('.streamlit/users.yaml') as file:
|
||||
# cred_config = yaml.load(file, Loader=SafeLoader)
|
||||
|
||||
file_content = read_text_file_from_s3('chatbot-editais-auth', 'config.yaml')
|
||||
# Parse the YAML content safely
|
||||
cred_config = yaml.safe_load(file_content)
|
||||
|
||||
# Pre-hashing all plain text passwords once
|
||||
# hash_credentials = stauth.Hasher.hash_passwords(config['credentials'])
|
||||
|
||||
authenticator = stauth.Authenticate(
|
||||
cred_config['credentials'],
|
||||
cred_config['cookie']['name'],
|
||||
cred_config['cookie']['key'],
|
||||
cred_config['cookie']['expiry_days']
|
||||
)
|
||||
return authenticator
|
||||
|
||||
def st_authenticate(authenticator: stauth.Authenticate):
|
||||
# authenticator = get_authenticator()
|
||||
try:
|
||||
authenticator.login(
|
||||
location='sidebar',
|
||||
fields=dict(Username="Usuário",
|
||||
Password="Senha")
|
||||
)
|
||||
except Exception as e:
|
||||
st.error(e)
|
||||
authenticator.cookie_controller.delete_cookie()
|
||||
st.warning('Caso o erro persistir, tente recarregar a página.')
|
||||
st.stop()
|
||||
|
||||
if st.session_state['authentication_status']:
|
||||
with st.sidebar:
|
||||
st.write(f'Usuário: {st.session_state["name"]}')
|
||||
authenticator.logout()
|
||||
elif st.session_state['authentication_status'] is False:
|
||||
with st.sidebar:
|
||||
st.error('Usuário/senha incorreto')
|
||||
st.stop()
|
||||
elif st.session_state['authentication_status'] is None:
|
||||
st.warning('Por favor, informe o seu usuário e senha no painel lateral')
|
||||
st.stop()
|
||||
def read_text_file_from_s3(bucket, key):
|
||||
"""
|
||||
Read a YAML file from an S3 bucket using provided AWS credentials.
|
||||
|
||||
Args:
|
||||
bucket (str): Name of the S3 bucket
|
||||
key (str): Path to the YAML file in the bucket
|
||||
aws_access_key_id (str): AWS Access Key ID
|
||||
aws_secret_access_key (str): AWS Secret Access Key
|
||||
|
||||
Returns:
|
||||
dict: Parsed YAML content
|
||||
"""
|
||||
try:
|
||||
# Create an S3 client
|
||||
s3_client = boto3.client('s3')
|
||||
|
||||
# Download the file from S3
|
||||
response = s3_client.get_object(Bucket=bucket, Key=key)
|
||||
|
||||
# Read the file content
|
||||
file_content = response['Body'].read().decode('utf-8')
|
||||
|
||||
return file_content
|
||||
|
||||
except Exception as e:
|
||||
st.error(f"Error reading file from S3: {e}")
|
||||
return None
|
||||
|
||||
def get_secret():
|
||||
|
||||
secret_name = "assistente-produtos-servicos"
|
||||
region_name = "us-east-1"
|
||||
|
||||
# Create a Secrets Manager client
|
||||
session = boto3.session.Session()
|
||||
client = session.client(
|
||||
service_name='secretsmanager',
|
||||
region_name=region_name
|
||||
)
|
||||
|
||||
try:
|
||||
get_secret_value_response = client.get_secret_value(
|
||||
SecretId=secret_name
|
||||
)
|
||||
except ClientError as e:
|
||||
# For a list of exceptions thrown, see
|
||||
# https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
|
||||
raise e
|
||||
|
||||
secret = get_secret_value_response['SecretString']
|
||||
return secret
|
||||
Reference in New Issue
Block a user