joaopaulopresa commited on
Commit
52beb16
1 Parent(s): 79ebcf2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -2
app.py CHANGED
@@ -1,4 +1,157 @@
1
  import streamlit as st
 
 
 
 
2
 
3
- x = st.slider('Select a value')
4
- st.write(x, 'squared is', x * x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import json
3
+ from data_module import faq_data, model_options
4
+ import uuid
5
+ from chat_handler import ChatHandler
6
 
7
+ chat = ChatHandler()
8
+ def add_custom_css():
9
+ st.markdown("""
10
+ <style>
11
+ .css-1d391kg { width: 35%; }
12
+ </style>
13
+ """, unsafe_allow_html=True)
14
+ def generate_user_id():
15
+ new_id = chat.generate_id()
16
+ return new_id
17
+
18
+ def clear_history(user_id):
19
+ chat.clear_history(user_id)
20
+ return 'response'
21
+
22
+ if 'user_id' not in st.session_state:
23
+ st.session_state['user_id'] = generate_user_id()
24
+
25
+ with open("embeddings_db_model.json", "r") as file:
26
+ embedding_models = json.load(file)
27
+ embedding_model_names = [model["model"] for model in embedding_models]
28
+
29
+ agent_types = [
30
+ 'JSON_CHAT_MODEL',
31
+ 'REACT_TEXT'
32
+ ]
33
+ selected_model = st.sidebar.selectbox("Escolha o Modelo LLM", model_options)
34
+ selected_embedding_model = st.sidebar.selectbox("Escolha o Modelo de Embedding", embedding_model_names)
35
+ selected_embedding_dir = next(item for item in embedding_models if item["model"] == selected_embedding_model)["dir"]
36
+ selected_agent_type = st.sidebar.selectbox("Escolha o Tipo de Agent", agent_types)
37
+
38
+
39
+ add_custom_css()
40
+ with st.sidebar:
41
+ st.write("## Opções de Controle")
42
+ if st.button('Limpar Histórico'):
43
+ # Fazer a requisição para limpar o histórico
44
+ response = clear_history(st.session_state['user_id'])
45
+ if response:
46
+ st.session_state.messages = [{"role": "assistant", "content": "Histórico limpo. Pode começar uma nova conversa."}]
47
+ st.rerun()
48
+ else:
49
+ st.error("Erro ao limpar o histórico")
50
+ with st.container():
51
+ col1, col2 = st.columns([1, 1])
52
+ with col1:
53
+ st.caption("LLM:")
54
+ st.write(selected_model)
55
+ with col2:
56
+ st.caption("Embeddings:")
57
+ st.write(selected_embedding_model)
58
+
59
+ st.title("⚖️ ChatBot Direito Tributário")
60
+ st.caption("Direito Tributário da Pessoa Jurídica")
61
+ st.caption("Projeto do Workshop de LLM UFG")
62
+
63
+
64
+
65
+ if "messages" not in st.session_state:
66
+ st.session_state["messages"] = [{"role": "assistant", "content": "Olá como posso ajudar?"}]
67
+ if "faq_question" not in st.session_state:
68
+ st.session_state["faq_question"] = None
69
+
70
+ # Input de chat do usuário
71
+ for msg in st.session_state.messages:
72
+ if msg['role'] == 'assistant':
73
+ img = "server_icon.png"
74
+ else:
75
+ img = 'user_icon.png'
76
+ st.chat_message(msg["role"],avatar=img).write(msg["content"])
77
+
78
+ def process_question(question):
79
+ st.session_state.messages.append({"role": "user", "content": question})
80
+ st.chat_message("user", avatar="user_icon.png").write(question)
81
+
82
+ with st.chat_message("assistant", avatar="server_icon.png"):
83
+ with st.spinner("Thinking..."):
84
+ data = dict(
85
+ user_id=st.session_state['user_id'],
86
+ text= question,
87
+ embedding_model= selected_embedding_model,
88
+ embedding_dir= selected_embedding_dir,
89
+ model= selected_model,
90
+ agent_type=selected_agent_type
91
+ )
92
+
93
+ msg,intermediary_steps = chat.post_message(message=data)
94
+ st.write(str(msg))
95
+ st.session_state.messages.append({"role": "assistant", "content": msg})
96
+ # Adicionando os passos intermediários
97
+ #intermediary_steps = response['response']['intermediate_steps']
98
+ # intermediary_steps = []
99
+
100
+ if intermediary_steps:
101
+ with st.expander("Ver Passos Intermediários"):
102
+ if intermediary_steps[0] == 'erro':
103
+ st.markdown("## ERROR...\n")
104
+ else:
105
+ st.markdown("## > Entering new AgentExecutor chain...\n")
106
+ for index, step in enumerate(intermediary_steps, start=1):
107
+ # action = step[0].get('tool', 'Unknown')
108
+ action = step[0].tool if hasattr(step[0], 'tool') else 'Unknown'
109
+ # action_input = step[0].get('tool_input', 'N/A')
110
+ # log = step[0].get('log', 'No log available')
111
+ action_input = step[0].tool_input if hasattr(step[0], 'tool_input') else 'N/A'
112
+ log = step[0].log if hasattr(step[0], 'log') else 'No log available'
113
+ st.markdown(f"**Passo {index}:**")
114
+ st.markdown(f" **Ação:** `{action}`")
115
+ st.markdown(f" **Entrada da Ação:** `{action_input}`")
116
+ st.code(log, language='json')
117
+ st.markdown("---")
118
+ # Adiciona a ação "Final Answer" ao final dos passos
119
+ st.markdown("**Ação:** Final Answer")
120
+ st.markdown(f"**Entrada da Ação:** `{msg}`")
121
+ st.markdown("## > Finished chain.")
122
+ else:
123
+ with st.expander("Ver Passos Intermediários"):
124
+ st.markdown("#### > Entering new AgentExecutor chain...\n")
125
+ st.markdown("**Ação:** Final Answer")
126
+ st.markdown(f"**Entrada da Ação:** `{msg}`")
127
+ st.markdown("#### > Finished chain...")
128
+
129
+ def add_faq_question_to_chat(question):
130
+ st.session_state["faq_question"] = question
131
+
132
+ # Barra lateral com perguntas frequentes
133
+ with st.sidebar:
134
+ st.write("## Perguntas Frequentes")
135
+ for index, item in enumerate(faq_data, start=1):
136
+ question_with_number = f"{index}\. {item['question']}"
137
+ expander = st.expander(question_with_number, expanded=False)
138
+
139
+ with expander:
140
+ st.write(item["answer"])
141
+ button_key = f"button_{index}"
142
+ if st.button("Enviar esta pergunta", key=button_key):
143
+ st.session_state['selected_question'] = item["question"]
144
+
145
+ if 'selected_question' in st.session_state and st.session_state['selected_question']:
146
+ add_faq_question_to_chat(st.session_state['selected_question'])
147
+ del st.session_state['selected_question']
148
+
149
+
150
+
151
+ if st.session_state["faq_question"]:
152
+ process_question(st.session_state["faq_question"])
153
+ st.session_state["faq_question"] = None
154
+
155
+
156
+ if prompt := st.chat_input():
157
+ process_question(prompt)