Spaces:
Runtime error
Runtime error
Commit ·
ceca01b
1
Parent(s): a37b230
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136#!/usr/bin/env python3import csvfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.vectorstores import FAISSfrom langchain.llms import OpenAIfrom langchain.chat_models import ChatOpenAIfrom langchain.vectorstores import Pineconefrom langchain.chains import RetrievalQAimport osimport gradio as grimport timefrom fuzzywuzzy import fuzzimport pineconefrom getpass import getpass
os.environ["OPENAI_API_KEY"] = "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"YOUR_API_KEY = "7fd42be9-4380-44f0-8f9e-c6f6a9c2f088"YOUR_ENV = "northamerica-northeast1-gcp"
index_name = 'knowledgebase'pinecone.init( api_key=YOUR_API_KEY, environment=YOUR_ENV)
faiss_index_folder_path = "/Users/axelwindbrake/Desktop/AI Automation folders/Chatbot Ver 3/Memory/faiss_index"
model_name = 'text-embedding-ada-002'
embed = OpenAIEmbeddings( model=model_name, openai_api_key=os.environ["OPENAI_API_KEY"])text_field = "text"res = embed.embed_documents(text_field)
# switch back to normal index for langchainindex = pinecone.Index(index_name)
vectorstore = Pinecone(index, embed.embed_query, text_field)
llm = ChatOpenAI( openai_api_key=os.environ["OPENAI_API_KEY"], model_name='gpt-4', temperature=0.5 , max_tokens=450)
qa = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=vectorstore.as_retriever())
inputs = gr.inputs.Textbox(lines=7, label="Frage:")outputs = gr.outputs.Textbox(label="Antwort")
query = inputs
def answer_question(query): result = vectorstore.similarity_search(query, k=3) llm = ChatOpenAI( openai_api_key=os.environ["OPENAI_API_KEY"], model_name='gpt-4', temperature=0.5 , max_tokens=850 ) qa = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=vectorstore.as_retriever() ) answer = qa.run(query) return {"answer": answer} # Return the result as a dictionary with an "answer" key
with gr.Blocks() as demo: chatbot = gr.Chatbot() msg = gr.Textbox() clear = gr.Button("Clear") def respond(message, chat_history): # If the message starts with "??", skip the CSV lookup if not message.startswith("??"): # Check if the question already has an answer in the CSV file with open("q&a.csv", "r", newline='') as f: reader = csv.reader(f) for row in reader: if fuzz.token_set_ratio(row[0], message) > 80: # Adjust the threshold as needed bot_message = row[1] break else: # If the question doesn't have an answer in the CSV file, proceed with the existing process bot_response = answer_question(message) if isinstance(bot_response, dict) and "answer" in bot_response: bot_message = bot_response["answer"] else: bot_message = "Sorry, I couldn't generate a response." else: # If the message starts with "??", remove the "??" and proceed with the existing process message = message[2:] bot_response = answer_question(message) if isinstance(bot_response, dict) and "answer" in bot_response: bot_message = bot_response["answer"] else: bot_message = "Sorry, I couldn't generate a response." # Save to CSV file with open("q&a.csv", "a", newline='') as f: writer = csv.writer(f) writer.writerow([message, bot_message]) chat_history.append((message, bot_message)) time.sleep(1) return "", chat_history msg.submit(respond, [msg, chatbot], [msg, chatbot]) clear.click(lambda: None, None, chatbot, queue=False)
with gr.Blocks() as demo: instructions = gr.Markdown("## Willkommen zur Vertriebs Knowledgebase\n\n\nBitte stelle deine Frage in der Textbox unten. \n\n\nAntworten werden zunächst in den gespeicherten Chatverläufen gesucht - wenn du das nicht möchtest, beginne deine Frage mit '??'.") chatbot = gr.Chatbot() msg = gr.Textbox() clear = gr.Button("Clear") msg.submit(respond, [msg, chatbot], [msg, chatbot]) clear.click(lambda: None, None, chatbot, queue=False) if __name__ == "__main__": demo.launch(share=True, inbrowser=True) app.pyAdded+136