jleitefilho commited on
Commit
9856885
·
verified ·
1 Parent(s): de594c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -132
app.py CHANGED
@@ -1,136 +1,215 @@
1
- # Projeto 6 - Construção e Deploy de Interface Web Para Agente de Conversação e Busca com LangChain e LLM
2
-
3
- # Framework para criação de aplicações web
4
- import streamlit as st
5
-
6
- # Para criação e execução de agentes conversacionais
7
- from langchain.agents import ConversationalChatAgent, AgentExecutor
8
-
9
- # Callback para interação com a interface do Streamlit
10
- from langchain_community.callbacks import StreamlitCallbackHandler
11
-
12
- # Integração com o modelo de linguagem da OpenAI
13
- from langchain_openai import ChatOpenAI
14
-
15
- # Memória para armazenar o histórico de conversa
16
- from langchain.memory import ConversationBufferMemory
17
-
18
- # Histórico de mensagens para o Streamlit
19
- from langchain_community.chat_message_histories import StreamlitChatMessageHistory
20
-
21
- # Ferramenta de busca DuckDuckGo para o agente
22
- from langchain_community.tools import DuckDuckGoSearchRun
23
-
24
- # Pacote para manipulação dos dados em formato JSON
25
- import json
26
-
27
- # Pacote para requisições
28
- import requests
29
-
30
- # Remove warnings
31
- import warnings
32
- warnings.filterwarnings('ignore')
33
-
34
- # Configuração do título da página
35
- st.set_page_config(page_title = "DSA")
36
-
37
- # Criação de colunas para layout da página
38
- # Define a proporção das colunas
39
- col1, col4 = st.columns([4, 1])
40
-
41
- # Configuração da primeira coluna para exibir o título do projeto
42
- with col1:
43
- st.title("Deploy UI Web para Chatbot com LangChain e LLM")
44
-
45
- # Campo para entrada da chave de API da OpenAI
46
- openai_api_key = st.sidebar.text_input("OpenAI API Key", type = "password")
47
-
48
- # Inicialização do histórico de mensagens
49
- # https://python.langchain.com/docs/integrations/memory/streamlit_chat_message_history/
50
- msgs = StreamlitChatMessageHistory()
51
-
52
- # Configuração da memória do chat
53
- # https://python.langchain.com/docs/modules/memory/types/buffer/
54
- memory = ConversationBufferMemory(chat_memory = msgs,
55
- return_messages = True,
56
- memory_key = "chat_history",
57
- output_key = "output")
58
-
59
- # Verificação para limpar o histórico de mensagens ou iniciar a conversa
60
- if len(msgs.messages) == 0 or st.sidebar.button("Reset"):
61
- msgs.clear()
62
- msgs.add_ai_message("Como eu posso ajudar você?")
63
- st.session_state.steps = {}
64
-
65
- # Definição de avatares para os participantes da conversa
66
- avatars = {"human": "user", "ai": "assistant"}
67
-
68
- # Loop para exibir mensagens no chat
69
- # Itera sobre cada mensagem no histórico de mensagens
70
- for idx, msg in enumerate(msgs.messages):
71
-
72
- # Cria uma mensagem no chat com o avatar correspondente ao tipo de usuário (humano ou IA)
73
- with st.chat_message(avatars[msg.type]):
74
-
75
- # Itera sobre os passos armazenados para cada mensagem, se houver
76
- for step in st.session_state.steps.get(str(idx), []):
77
-
78
- # Se o passo atual indica uma exceção, pula para o próximo passo
79
- if step[0].tool == "_Exception":
80
- continue
81
-
82
- # Cria um expander para cada ferramenta usada na resposta, mostrando o input
83
- with st.expander(f"✅ **{step[0].tool}**: {step[0].tool_input}"):
84
-
85
- # Exibe o log de execução da ferramenta
86
- st.write(step[0].log)
87
-
88
- # Exibe o resultado da execução da ferramenta
89
- st.write(f"**{step[1]}**")
90
-
91
- # Exibe o conteúdo da mensagem no chat
92
- st.write(msg.content)
93
-
94
- # Campo de entrada para novas mensagens do usuário
95
- if prompt := st.chat_input(placeholder = "Digite uma pergunta para começar!"):
96
- st.chat_message("user").write(prompt)
97
-
98
- # Verificação da chave de API
99
- if not openai_api_key:
100
- st.info("Adicione sua OpenAI API key para continuar.")
101
- st.stop()
102
-
103
- # Configuração do modelo de linguagem da OpenAI
104
- # https://python.langchain.com/docs/integrations/chat/openai/
105
- llm_dsa = ChatOpenAI(openai_api_key = openai_api_key, streaming = True)
106
-
107
- # Configuração da ferramenta de busca do agente
108
- # https://api.python.langchain.com/en/latest/tools/langchain_community.tools.ddg_search.tool.DuckDuckGoSearchRun.html
109
- mecanismo_busca = [DuckDuckGoSearchRun(name = "Search")]
110
 
111
- # Criação do agente conversacional com a ferramenta de busca
112
- # https://api.python.langchain.com/en/latest/agents/langchain.agents.conversational_chat.base.ConversationalChatAgent.html
113
- chat_dsa_agent = ConversationalChatAgent.from_llm_and_tools(llm = llm_dsa, tools = mecanismo_busca)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
- # Executor para o agente, incluindo memória e tratamento de erros
116
- # https://api.python.langchain.com/en/latest/agents/langchain.agents.agent.AgentExecutor.html
117
- executor = AgentExecutor.from_agent_and_tools(agent = chat_dsa_agent,
118
- tools = mecanismo_busca,
119
- memory = memory,
120
- return_intermediate_steps = True,
121
- handle_parsing_errors = True)
122
 
123
- # Exibição da resposta do assistente
124
- with st.chat_message("assistant"):
125
-
126
- # Callback para o Streamlit
127
- # https://api.python.langchain.com/en/latest/callbacks/langchain_community.callbacks.streamlit.streamlit_callback_handler.StreamlitCallbackHandler.html
128
- st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts = False)
129
- response = executor(prompt, callbacks = [st_cb])
130
- st.write(response["output"])
131
-
132
- # Armazenamento dos passos intermediários
133
- st.session_state.steps[str(len(msgs.messages) - 1)] = response["intermediate_steps"]
134
-
135
- # Fim
 
 
 
 
 
 
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ api_token = os.getenv("HF_TOKEN")
4
+
5
+ from langchain_community.vectorstores import FAISS
6
+ from langchain_community.document_loaders import PyPDFLoader
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain_community.vectorstores import Chroma
9
+ from langchain.chains import ConversationalRetrievalChain
10
+ from langchain_community.embeddings import HuggingFaceEmbeddings
11
+ from langchain_community.llms import HuggingFacePipeline
12
+ from langchain.chains import ConversationChain
13
+ from langchain.memory import ConversationBufferMemory
14
+ from langchain_community.llms import HuggingFaceEndpoint
15
+ import torch
16
+
17
+ list_llm = ["meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.2"]
18
+ list_llm_simple = [os.path.basename(llm) for llm in list_llm]
19
+
20
+ # Load and split PDF document
21
+ def load_doc(list_file_path):
22
+ # Processing for one document only
23
+ # loader = PyPDFLoader(file_path)
24
+ # pages = loader.load()
25
+ loaders = [PyPDFLoader(x) for x in list_file_path]
26
+ pages = []
27
+ for loader in loaders:
28
+ pages.extend(loader.load())
29
+ text_splitter = RecursiveCharacterTextSplitter(
30
+ chunk_size = 1024,
31
+ chunk_overlap = 64
32
+ )
33
+ doc_splits = text_splitter.split_documents(pages)
34
+ return doc_splits
35
+
36
+ # Create vector database
37
+ def create_db(splits):
38
+ embeddings = HuggingFaceEmbeddings()
39
+ vectordb = FAISS.from_documents(splits, embeddings)
40
+ return vectordb
41
+
42
+
43
+ # Initialize langchain LLM chain
44
+ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
45
+ if llm_model == "meta-llama/Meta-Llama-3-8B-Instruct":
46
+ llm = HuggingFaceEndpoint(
47
+ repo_id=llm_model,
48
+ huggingfacehub_api_token = api_token,
49
+ temperature = temperature,
50
+ max_new_tokens = max_tokens,
51
+ top_k = top_k,
52
+ )
53
+ else:
54
+ llm = HuggingFaceEndpoint(
55
+ huggingfacehub_api_token = api_token,
56
+ repo_id=llm_model,
57
+ temperature = temperature,
58
+ max_new_tokens = max_tokens,
59
+ top_k = top_k,
60
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ memory = ConversationBufferMemory(
63
+ memory_key="chat_history",
64
+ output_key='answer',
65
+ return_messages=True
66
+ )
67
+
68
+ retriever=vector_db.as_retriever()
69
+ qa_chain = ConversationalRetrievalChain.from_llm(
70
+ llm,
71
+ retriever=retriever,
72
+ chain_type="stuff",
73
+ memory=memory,
74
+ return_source_documents=True,
75
+ verbose=False,
76
+ )
77
+ return qa_chain
78
+
79
+ # Initialize database
80
+ def initialize_database(list_file_obj, progress=gr.Progress()):
81
+ # Create a list of documents (when valid)
82
+ list_file_path = [x.name for x in list_file_obj if x is not None]
83
+ # Load document and create splits
84
+ doc_splits = load_doc(list_file_path)
85
+ # Create or load vector database
86
+ vector_db = create_db(doc_splits)
87
+ return vector_db, "Database created!"
88
+
89
+ # Initialize LLM
90
+ def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
91
+ # print("llm_option",llm_option)
92
+ llm_name = list_llm[llm_option]
93
+ print("llm_name: ",llm_name)
94
+ qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
95
+ return qa_chain, "QA chain initialized. Chatbot is ready!"
96
+
97
+
98
+ def format_chat_history(message, chat_history):
99
+ formatted_chat_history = []
100
+ for user_message, bot_message in chat_history:
101
+ formatted_chat_history.append(f"User: {user_message}")
102
+ formatted_chat_history.append(f"Assistant: {bot_message}")
103
+ return formatted_chat_history
104
 
 
 
 
 
 
 
 
105
 
106
+ def conversation(qa_chain, message, history):
107
+ formatted_chat_history = format_chat_history(message, history)
108
+ # Generate response using QA chain
109
+ response = qa_chain.invoke({"question": message, "chat_history": formatted_chat_history})
110
+ response_answer = response["answer"]
111
+ if response_answer.find("Helpful Answer:") != -1:
112
+ response_answer = response_answer.split("Helpful Answer:")[-1]
113
+ response_sources = response["source_documents"]
114
+ response_source1 = response_sources[0].page_content.strip()
115
+ response_source2 = response_sources[1].page_content.strip()
116
+ response_source3 = response_sources[2].page_content.strip()
117
+ # Langchain sources are zero-based
118
+ response_source1_page = response_sources[0].metadata["page"] + 1
119
+ response_source2_page = response_sources[1].metadata["page"] + 1
120
+ response_source3_page = response_sources[2].metadata["page"] + 1
121
+ # Append user message and response to chat history
122
+ new_history = history + [(message, response_answer)]
123
+ return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
124
+
125
 
126
+ def upload_file(file_obj):
127
+ list_file_path = []
128
+ for idx, file in enumerate(file_obj):
129
+ file_path = file_obj.name
130
+ list_file_path.append(file_path)
131
+ return list_file_path
132
+
133
+
134
+ def demo():
135
+ # with gr.Blocks(theme=gr.themes.Default(primary_hue="sky")) as demo:
136
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink", neutral_hue = "sky")) as demo:
137
+ vector_db = gr.State()
138
+ qa_chain = gr.State()
139
+ gr.HTML("<center><h1>RAG PDF chatbot</h1><center>")
140
+ gr.Markdown("""<b>Query your PDF documents!</b> This AI agent is designed to perform retrieval augmented generation (RAG) on PDF documents. The app is hosted on Hugging Face Hub for the sole purpose of demonstration. \
141
+ <b>Please do not upload confidential documents.</b>
142
+ """)
143
+ with gr.Row():
144
+ with gr.Column(scale = 86):
145
+ gr.Markdown("<b>Step 1 - Upload PDF documents and Initialize RAG pipeline</b>")
146
+ with gr.Row():
147
+ document = gr.Files(height=300, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload PDF documents")
148
+ with gr.Row():
149
+ db_btn = gr.Button("Create vector database")
150
+ with gr.Row():
151
+ db_progress = gr.Textbox(value="Not initialized", show_label=False) # label="Vector database status",
152
+ gr.Markdown("<style>body { font-size: 16px; }</style><b>Select Large Language Model (LLM) and input parameters</b>")
153
+ with gr.Row():
154
+ llm_btn = gr.Radio(list_llm_simple, label="Available LLMs", value = list_llm_simple[0], type="index") # info="Select LLM", show_label=False
155
+ with gr.Row():
156
+ with gr.Accordion("LLM input parameters", open=False):
157
+ with gr.Row():
158
+ slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.5, step=0.1, label="Temperature", info="Controls randomness in token generation", interactive=True)
159
+ with gr.Row():
160
+ slider_maxtokens = gr.Slider(minimum = 128, maximum = 9192, value=4096, step=128, label="Max New Tokens", info="Maximum number of tokens to be generated",interactive=True)
161
+ with gr.Row():
162
+ slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k", info="Number of tokens to select the next token from", interactive=True)
163
+ with gr.Row():
164
+ qachain_btn = gr.Button("Initialize Question Answering Chatbot")
165
+ with gr.Row():
166
+ llm_progress = gr.Textbox(value="Not initialized", show_label=False) # label="Chatbot status",
167
+
168
+ with gr.Column(scale = 200):
169
+ gr.Markdown("<b>Step 2 - Chat with your Document</b>")
170
+ chatbot = gr.Chatbot(height=505)
171
+ with gr.Accordion("Relevent context from the source document", open=False):
172
+ with gr.Row():
173
+ doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
174
+ source1_page = gr.Number(label="Page", scale=1)
175
+ with gr.Row():
176
+ doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
177
+ source2_page = gr.Number(label="Page", scale=1)
178
+ with gr.Row():
179
+ doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
180
+ source3_page = gr.Number(label="Page", scale=1)
181
+ with gr.Row():
182
+ msg = gr.Textbox(placeholder="Ask a question", container=True)
183
+ with gr.Row():
184
+ submit_btn = gr.Button("Submit")
185
+ clear_btn = gr.ClearButton([msg, chatbot], value="Clear")
186
+
187
+ # Preprocessing events
188
+ db_btn.click(initialize_database, \
189
+ inputs=[document], \
190
+ outputs=[vector_db, db_progress])
191
+ qachain_btn.click(initialize_LLM, \
192
+ inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
193
+ outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
194
+ inputs=None, \
195
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
196
+ queue=False)
197
+
198
+ # Chatbot events
199
+ msg.submit(conversation, \
200
+ inputs=[qa_chain, msg, chatbot], \
201
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
202
+ queue=False)
203
+ submit_btn.click(conversation, \
204
+ inputs=[qa_chain, msg, chatbot], \
205
+ outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
206
+ queue=False)
207
+ clear_btn.click(lambda:[None,"",0,"",0,"",0], \
208
+ inputs=None, \
209
+ outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
210
+ queue=False)
211
+ demo.queue().launch(debug=True)
212
+
213
+
214
+ if __name__ == "__main__":
215
+ demo()