Lailson commited on
Commit
a12f2a5
·
1 Parent(s): 8e40526

initial commit

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