Skip to content

Commit 22eb2f6

Browse files
Merge pull request #38 from basedosdados/add-env-variables
chore: add env variables
2 parents a310dad + 5594060 commit 22eb2f6

File tree

9 files changed

+108
-66
lines changed

9 files changed

+108
-66
lines changed

.env.example

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Backend API host and port
2+
API_HOST=localhost
3+
API_PORT=8000
4+
5+
# Log level
6+
LOG_LEVEL=DEBUG
7+
8+
# Whether the full stacktrace should be shown when logging exceptions.
9+
LOG_BACKTRACE=true
10+
11+
# Whether exception traces should display the variables values,
12+
# for debugging. Should be se to False in production.
13+
LOG_DIAGNOSE=false
14+
15+
# Whether the messages to be logged should first pass through
16+
# a multiprocessing-safe queue before reaching the sink.
17+
LOG_ENQUEUE=true

.github/workflows/deploy-dev.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,13 @@ jobs:
5959
name: ghcr.io/${{ github.repository }}
6060
tag: dev
6161
pullPolicy: Always
62+
env:
63+
API_HOST: api-development-service
64+
API_PORT: 80
65+
LOG_LEVEL: INFO
66+
LOG_BACKTRACE: true
67+
LOG_DIAGNOSE: false
68+
LOG_ENQUEUE: true
6269
replicas: 1
6370
resources:
6471
requests:

README.md

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,33 @@
11
# Interface do Chatbot da BD, feita com [Streamlit](https://streamlit.io/)
22

33
## Instruções
4-
A interface do chatbot pode ser executada localmente utilizando o Docker ou o Python.
4+
Copie o arquivo `.env.example` e ajuste os valores:
5+
```bash
6+
cp .env.example .env
7+
```
8+
Em seguida, execute a aplicação localmente utilizando o Docker ou o Python.
59

610
### Docker
7-
Instale o Docker seguindo as [instruções de instalação](https://docs.docker.com/engine/install/), de acordo com a distribuição linux que você usa. Em seguida, a partir da raiz deste repositório, execute os comandos:
11+
Instale o Docker seguindo as [instruções de instalação](https://docs.docker.com/engine/install/), de acordo com a distribuição linux que você usa. Em seguida, a partir da raiz do repositório, construa a imagem:
12+
```bash
13+
docker build -t nome-da-tag:latest .
814
```
9-
docker build -t <nome-da-tag>:latest .
10-
docker run <nome-da-tag>:latest
15+
E execute o container:
16+
```bash
17+
docker run --env-file .env -p 8501:8501 nome-da-tag:latest
1118
```
19+
A aplicação estará disponível em `http://localhost:8501`
20+
1221
> [!TIP]
1322
> Você pode adicionar a flag `--rm` ao comando `docker run` para remover o container após a sua execução.
1423
### Python
1524

16-
Crie um ambiente virtual e ative-o:
17-
```
18-
python3 -m venv <caminho-para-o-venv>
19-
. <caminho-para-o-venv>/bin/activate
20-
```
21-
Em seguida, a partir da raíz deste repositório, instale o pacote:
22-
```
23-
pip install --upgrade pip
24-
pip install .
25-
```
26-
E execute-o utilizando o streamlit:
25+
Instale o [Poetry](https://python-poetry.org/docs/). Em seguida, a partir da raíz do repositório, instale o pacote:
26+
```bash
27+
poetry install
2728
```
29+
30+
E execute a aplicação utilizando o streamlit:
31+
```bash
2832
streamlit run frontend/main.py
2933
```
30-
> [!TIP]
31-
> - Você pode adicionar a flag `-e` para instalar o pacote no modo editável durante o desenvolvimento.
32-
> - Você pode criar o ambiente virtual e fazer a instalação do pacote utilizando ferramentas como o [uv](https://docs.astral.sh/uv/) ou o [poetry](https://python-poetry.org/docs/).

charts/basedosdados-chatbot-frontend/templates/deployment.yaml

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,16 @@ spec:
3434
ports:
3535
- name: streamlit
3636
containerPort: 8501
37-
volumeMounts:
38-
- name: chatbot-log-volume
39-
mountPath: /var/log/chatbot
37+
env:
38+
{{- $env := .Values.chatbotFrontend.env | default dict }}
39+
- name: API_HOST
40+
value: {{ required ".Values.chatbotFrontend.env.API_HOST is required" $env.API_HOST | quote }}
41+
- name: API_PORT
42+
value: {{ required ".Values.chatbotFrontend.env.API_PORT is required" $env.API_PORT | quote }}
43+
{{- range $key, $value := omit $env "API_HOST" "API_PORT" }}
44+
- name: {{ $key }}
45+
value: {{ $value | quote }}
46+
{{- end }}
4047
{{- with .Values.chatbotFrontend.resources }}
4148
resources:
4249
{{- toYaml . | nindent 12 }}
@@ -53,9 +60,4 @@ spec:
5360
port: 8501
5461
initialDelaySeconds: 10
5562
periodSeconds: 10
56-
# TODO: use persistent volume
57-
volumes:
58-
- name: chatbot-log-volume
59-
emptyDir:
60-
sizeLimit: 500Mi
6163
restartPolicy: Always

charts/basedosdados-chatbot-frontend/values.yaml

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,25 @@ chatbotFrontend:
99
tag: stable
1010
pullPolicy: Always
1111

12+
# Environment variables
13+
env:
14+
API_HOST: localhost
15+
API_PORT: 8000
16+
LOG_LEVEL: DEBUG
17+
LOG_BACKTRACE: true
18+
LOG_DIAGNOSE: false
19+
LOG_ENQUEUE: true
20+
1221
# Number of replicas
1322
replicas: 1
1423

1524
# Resource specification
1625
resources:
1726
requests:
18-
cpu: 1
27+
cpu: 250m
1928
memory: 500Mi
2029
limits:
21-
cpu: 1
30+
cpu: 500m
2231
memory: 1Gi
2332

2433
# Ingress configuration

frontend/main.py

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,19 @@
1+
import sys
12
import time
23
from functools import cache
3-
from pathlib import Path
44

55
import streamlit as st
66
from loguru import logger
77

88
from frontend.api import APIClient
99
from frontend.components.chat_page import ChatPage
1010
from frontend.utils.constants import (BASE_URL, LOG_BACKTRACE, LOG_DIAGNOSE,
11-
LOG_ENQUEUE, LOG_FILE_PATH, LOG_LEVEL,
12-
LOG_RETENTION, LOG_ROTATION, NEW_CHAT)
11+
LOG_ENQUEUE, LOG_LEVEL, NEW_CHAT)
1312
from frontend.utils.logos import BD_LOGO
1413

1514

1615
@cache
1716
def _setup_logger():
18-
# Create log directory
19-
log_path = Path(LOG_FILE_PATH)
20-
log_path.parent.mkdir(parents=True, exist_ok=True)
21-
2217
# Remove default handler
2318
logger.remove()
2419

@@ -37,11 +32,9 @@ def _format(record):
3732

3833
# Add handler to logger
3934
logger.add(
40-
sink=LOG_FILE_PATH,
35+
sink=sys.stdout,
4136
level=LOG_LEVEL,
4237
format=_format,
43-
rotation=LOG_ROTATION,
44-
retention=LOG_RETENTION,
4538
backtrace=LOG_BACKTRACE,
4639
diagnose=LOG_DIAGNOSE,
4740
enqueue=LOG_ENQUEUE
@@ -109,27 +102,27 @@ def about():
109102

110103
st.write("\n")
111104

112-
st.subheader("Bem Vindo(a)! :wave:")
105+
st.subheader("Bem Vindo(a)! 👋")
113106
st.write(f"Bem vindo(a) ao chatbot da BD! Ele vai te ajudar a conversar com seus dados! Basta entrar na página de chat no menu à esquerda e começar a conversa. Faça perguntas sobre os dados disponíveis e o chatbot dará o seu melhor para respondê-las!", unsafe_allow_html=True)
114107

115108
st.write("\n")
116109

117110
# Available models
118-
st.subheader("Modelo :brain:")
111+
st.subheader("Modelo 🧠")
119112
st.write("O modelo por trás do chatbot é o Gemini, do Google.")
120113

121114
st.write("\n")
122115

123116
# Available features
124-
st.subheader("Funcionalidades :memo:")
117+
st.subheader("Funcionalidades 🛠️")
125118
st.write("""
126-
- **Feedback (:material/thumb_up: ou :material/thumb_down:):** Clique nos botões de feedback para enviar feedbacks sobre as respostas recebidas, com comentários opcionais.
127-
- **Excluir Conversa (:material/delete:):** Clique no botão de excluir conversa para excluir a conversa com o chatbot. Essa ação é irreversível."""
119+
- **Feedback (:material/thumb_up: ou :material/thumb_down:):** Clique nos botões de feedback para avaliar as respostas, com comentários opcionais.
120+
- **Excluir Conversa (:material/delete:):** Clique no botão de excluir conversa para excluir a conversa com o chatbot. As mensagens permanecerão salvas em nosso banco de dados para análise e melhoria do produto."""
128121
)
129122
st.write("\n")
130123

131124
# Prompting guide
132-
st.subheader("Guia de Prompt :clipboard:")
125+
st.subheader("Guia de Prompt 📋")
133126
st.write("A forma como você conversa com o chatbot pode influenciar na qualidade das respostas! Por isso, abaixo estão listadas algumas dicas para te ajudar a elaborar suas perguntas. Elas podem ser úteis caso as respostas fornecidas estejam incorretas ou não sejam boas o suficiente!")
134127
st.write("""
135128
1. Tente fazer uma pergunta por vez. Caso sua pergunta seja muito complexa, ou talvez seja um conjunto de várias perguntas, tente separá-la em perguntas menores e mais simples.
@@ -140,8 +133,8 @@ def about():
140133
st.write("\n")
141134

142135
# Important information
143-
st.subheader("Importante :pushpin:")
144-
st.info("Depois de enviar uma pergunta ao chatbot, espere até que uma resposta seja fornecida antes de trocar de página ou clicar em qualquer botão dentro da aplicação. Você pode alternar entre as abas do seu navegador normalmente.")
136+
st.subheader("Importante 📌")
137+
st.info("Depois de enviar uma pergunta ao chatbot, aguarde a resposta completa antes de trocar de página ou clicar em botões. Você pode alternar entre abas do navegador normalmente.")
145138

146139
if st.session_state.get("logged_in"):
147140
about_page = st.Page(page=about, title="Conheça o App", icon=":material/lightbulb_2:")

frontend/utils/constants.py

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,27 @@
1-
# API variables
2-
API_HOST = "api-development-service"
3-
API_PORT = 80
4-
BASE_URL = f"http://{API_HOST}:{API_PORT}" # Base API URL
1+
import os
52

6-
# Set log sink.
7-
LOG_FILE_PATH = "/var/log/chatbot/frontend.log"
3+
import dotenv
84

9-
# Set log level.
10-
LOG_LEVEL = "DEBUG"
5+
dotenv.load_dotenv()
116

12-
# Rotate logs daily.
13-
LOG_ROTATION = "1 day"
7+
# API variables
8+
API_HOST = os.environ["API_HOST"]
9+
API_PORT = os.environ["API_PORT"]
10+
BASE_URL = f"http://{API_HOST}:{API_PORT}" # Base API URL
1411

15-
# Don't delete old logs.
16-
LOG_RETENTION = None
12+
# Set log level
13+
LOG_LEVEL = os.getenv("LOG_LEVEL", "DEBUG")
1714

18-
# Whether the full stacktrace should be shown when logging exceptions.
19-
LOG_BACKTRACE = True
15+
# Whether the full stacktrace should be shown when logging exceptions
16+
LOG_BACKTRACE = os.getenv("LOG_BACKTRACE", "true").lower() == "true"
2017

2118
# Whether exception traces should display the variables values,
22-
# for debugging. Should be se to False in production.
23-
LOG_DIAGNOSE = False
19+
# for debugging. Should be se to False in production
20+
LOG_DIAGNOSE = os.getenv("LOG_DIAGNOSE", "false").lower() == "true"
2421

2522
# Whether the messages to be logged should first pass through
26-
# a multiprocessing-safe queue before reaching the sink.
27-
LOG_ENQUEUE = True
23+
# a multiprocessing-safe queue before reaching the sink
24+
LOG_ENQUEUE = os.getenv("LOG_ENQUEUE", "true").lower() == "true"
2825

29-
# Key for storing an empty chat page in the session state.
26+
# Key for storing an empty chat page in the session state
3027
NEW_CHAT = "new_chat"

poetry.lock

Lines changed: 16 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ dependencies = [
1111
"httpx (>=0.28.1,<0.29.0)",
1212
"loguru (>=0.7.3,<0.8.0)",
1313
"pydantic (>=2.11.7,<3.0.0)",
14+
"python-dotenv (>=1.2.1,<2.0.0)",
1415
"sqlparse (>=0.5.3,<0.6.0)",
1516
"streamlit (==1.49.0)",
1617
"streamlit-extras (==0.5.5)"

0 commit comments

Comments
 (0)