|
|
import os |
|
|
|
|
|
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") |
|
|
PINECONE_INDEX_NAME = os.getenv("PINECONE_INDEX_NAME") |
|
|
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY") |
|
|
|
|
|
import gradio as gr |
|
|
from langchain.text_splitter import RecursiveCharacterTextSplitter |
|
|
from langchain_openai import OpenAIEmbeddings,ChatOpenAI |
|
|
from langchain_pinecone import PineconeVectorStore |
|
|
from langchain.chains import ConversationalRetrievalChain |
|
|
from langchain.memory import ConversationBufferMemory |
|
|
from langchain.prompts import PromptTemplate |
|
|
|
|
|
|
|
|
model = ChatOpenAI(openai_api_key=OPENAI_API_KEY, model="gpt-3.5-turbo", ) |
|
|
embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY) |
|
|
|
|
|
vectorstore = PineconeVectorStore.from_existing_index(PINECONE_INDEX_NAME, embeddings) |
|
|
retriever = vectorstore.as_retriever() |
|
|
|
|
|
def create_conversation(query: str, chat_history: list) -> tuple: |
|
|
try: |
|
|
|
|
|
system_instruction = '''Você é um assistente pessoal e muito educado para responder a quaisquer perguntas sobre documentos da empresa Interfocus, respondendo sempre em português. |
|
|
Se a pergunta do usuário exigir que você forneça informações específicas dos documentos, dê sua resposta baseada apenas nos exemplos fornecidos. |
|
|
NÃO gere uma resposta que NÃO esteja escrita nos exemplos fornecidos.''' |
|
|
|
|
|
template = ( |
|
|
f"{system_instruction} " |
|
|
"Combine o histórico de chat e a pergunta em sequência em uma pergunta independente." |
|
|
"Histórico de chat: {chat_history}" |
|
|
"Pergunta independente: {question}" |
|
|
) |
|
|
|
|
|
condense_question_prompt = PromptTemplate.from_template(template) |
|
|
|
|
|
memory = ConversationBufferMemory( |
|
|
memory_key='chat_history', |
|
|
return_messages=True |
|
|
) |
|
|
|
|
|
qa_chain = ConversationalRetrievalChain.from_llm( |
|
|
llm=model, |
|
|
retriever=retriever, |
|
|
condense_question_prompt=condense_question_prompt, |
|
|
memory=memory, |
|
|
get_chat_history=lambda h: h, |
|
|
) |
|
|
|
|
|
result = qa_chain({'question': query, 'chat_history': chat_history}) |
|
|
chat_history.append((query, result['answer'])) |
|
|
return '', chat_history |
|
|
|
|
|
|
|
|
except Exception as e: |
|
|
chat_history.append((query, e)) |
|
|
return '', chat_history |
|
|
|
|
|
|
|
|
with gr.Blocks() as test: |
|
|
|
|
|
chatbot = gr.Chatbot(label='Chat Empresa Interfocus') |
|
|
msg = gr.Textbox() |
|
|
clear = gr.ClearButton([msg, chatbot]) |
|
|
|
|
|
msg.submit(create_conversation, [msg, chatbot], [msg, chatbot]) |
|
|
|
|
|
test.launch(debug=True) |