Upload app_okean.py
Browse files- app_okean.py +106 -0
app_okean.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pinecone
|
| 3 |
+
from langchain.vectorstores import Pinecone
|
| 4 |
+
from langchain.embeddings import OpenAIEmbeddings
|
| 5 |
+
from langchain.document_loaders import PyPDFLoader
|
| 6 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 7 |
+
from dotenv import load_dotenv, find_dotenv
|
| 8 |
+
load_dotenv(find_dotenv(), override=True)
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
import pinecone
|
| 12 |
+
import gradio as gr
|
| 13 |
+
from langchain.chains import LLMChain
|
| 14 |
+
from langchain.prompts import PromptTemplate
|
| 15 |
+
from langchain.chat_models import ChatOpenAI
|
| 16 |
+
from langchain.vectorstores import Pinecone
|
| 17 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 18 |
+
|
| 19 |
+
from dotenv import load_dotenv, find_dotenv
|
| 20 |
+
load_dotenv(find_dotenv(), override=True)
|
| 21 |
+
|
| 22 |
+
PINECONE_API_KEY = os.environ.get('PINECONE_API_KEY')
|
| 23 |
+
PINECONE_ENV = os.environ.get('PINECONE_ENV')
|
| 24 |
+
|
| 25 |
+
embeddings = OpenAIEmbeddings()
|
| 26 |
+
|
| 27 |
+
pinecone.init(
|
| 28 |
+
api_key=PINECONE_API_KEY,
|
| 29 |
+
environment=PINECONE_ENV
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
index_name = "okean"
|
| 33 |
+
index = pinecone.Index(index_name)
|
| 34 |
+
|
| 35 |
+
llm = ChatOpenAI(model='gpt-4-1106-preview', temperature=0)
|
| 36 |
+
|
| 37 |
+
template="""Assistente é uma IA que tira dúvidas de um manual e documentação. Os documentos tem conteudo em ingles e portugues mas responda sempre em português.
|
| 38 |
+
Assistente elabora repostas simplificadas, com base no contexto fornecido.
|
| 39 |
+
Assistente fornece referências extraídas do contexto abaixo.
|
| 40 |
+
Caso não consiga encontrar no contexto abaixo ou caso a pergunta não esteja relacionada do contexto do manual,
|
| 41 |
+
diga apenas 'Eu não sei!'
|
| 42 |
+
Pergunta: {query}
|
| 43 |
+
|
| 44 |
+
Contexto: {context}
|
| 45 |
+
Referência: [Página: {page}, Fonte: {source}]
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
prompt = PromptTemplate(
|
| 49 |
+
template=template,
|
| 50 |
+
input_variables=["query", "context", "page", "source"]
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
historico = []
|
| 54 |
+
|
| 55 |
+
def clear_history():
|
| 56 |
+
global historico
|
| 57 |
+
historico = []
|
| 58 |
+
return "Histórico limpo!", "Histórico de perguntas e respostas aqui..."
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def search(query):
|
| 62 |
+
global historico
|
| 63 |
+
# Adiciona a pergunta ao histórico
|
| 64 |
+
historico.append(f"Pergunta: {query}")
|
| 65 |
+
|
| 66 |
+
# Realiza a busca por similaridade
|
| 67 |
+
docsearch = Pinecone.from_existing_index(index_name, embeddings)
|
| 68 |
+
docs = docsearch.similarity_search(query, k=3)
|
| 69 |
+
|
| 70 |
+
first_doc = docs[0]
|
| 71 |
+
page_ref = first_doc.metadata['page']
|
| 72 |
+
source_ref = first_doc.metadata['source']
|
| 73 |
+
|
| 74 |
+
# Concatena o conteúdo das páginas com o histórico e inclui os metadados
|
| 75 |
+
context = ' '.join(historico)
|
| 76 |
+
for doc in docs:
|
| 77 |
+
print(doc)
|
| 78 |
+
context += f" {doc.page_content} [Referência: Página - {doc.metadata['page']}, Fonte - {doc.metadata['source']}]"
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# Chama a cadeia LLM com o novo contexto
|
| 82 |
+
resp = LLMChain(prompt=prompt, llm=llm)
|
| 83 |
+
answer = resp.run(query=query, context=context, page=page_ref, source=source_ref)
|
| 84 |
+
|
| 85 |
+
# Formatar a resposta para incluir as informações de página e fonte
|
| 86 |
+
formatted_answer = f"{answer}\n\nReferência: Página - {page_ref}, Fonte - {source_ref}"
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Adiciona a resposta ao histórico
|
| 90 |
+
historico.append(f"Resposta: {formatted_answer}")
|
| 91 |
+
|
| 92 |
+
# Retorne tanto a resposta quanto o histórico atualizado
|
| 93 |
+
return formatted_answer, "\n".join(historico)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
with gr.Blocks(title="Chatbot Inteligente", theme=gr.themes.Soft()) as ui:
|
| 98 |
+
gr.Markdown("# Sou uma IA que tem o manual OKEAN como base de conhecimento")
|
| 99 |
+
query = gr.Textbox(label='Faça a sua pergunta:', placeholder="EX: como funcionam o sistema de propulsão?")
|
| 100 |
+
text_output = gr.Textbox(label="Resposta")
|
| 101 |
+
historico_output = gr.Textbox(label="Histórico", value="Histórico de perguntas e respostas aqui...")
|
| 102 |
+
btn = gr.Button("Perguntar")
|
| 103 |
+
clear_btn = gr.Button("Limpar Histórico") # Novo botão para limpar o histórico
|
| 104 |
+
btn.click(fn=search, inputs=query, outputs=[text_output, historico_output])
|
| 105 |
+
clear_btn.click(fn=clear_history, inputs=[], outputs=[text_output, historico_output]) # Vincula a nova função ao botão
|
| 106 |
+
ui.launch(debug=True, share=True)
|