Ahmed-14 commited on
Commit
482d1ab
·
1 Parent(s): 6848687

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -0
app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # import logging
3
+ import os
4
+ os.environ['OPENAI_API_KEY'] = "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"
5
+ import openai
6
+ import json
7
+
8
+
9
+
10
+ from llama_index import GPTSimpleVectorIndex, LLMPredictor, PromptHelper, ServiceContext, QuestionAnswerPrompt
11
+ from langchain import OpenAI
12
+
13
+
14
+
15
+
16
+ from huggingface_hub import HfFileSystem
17
+ fs = HfFileSystem()
18
+
19
+ text_list = fs.ls("datasets/GoChat/Gochat247_Data/Data", detail=False)
20
+
21
+ from llama_index import Document
22
+ documents = [Document(t) for t in text_list]
23
+
24
+ # Setup your LLM
25
+
26
+
27
+ # define LLM
28
+ llm_predictor = LLMPredictor(llm=OpenAI(temperature=0, model_name="text-davinci-003"))
29
+
30
+ # define prompt helper
31
+ # set maximum input size
32
+ max_input_size = 4096
33
+ # set number of output tokens
34
+ num_output = 256
35
+ # set maximum chunk overlap
36
+ max_chunk_overlap = 20
37
+ prompt_helper = PromptHelper(max_input_size, num_output, max_chunk_overlap)
38
+
39
+ service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, prompt_helper=prompt_helper)
40
+
41
+
42
+ index = GPTSimpleVectorIndex.from_documents(documents, service_context=service_context)
43
+
44
+
45
+ ## Define Chat BOT Class to generate Response , handle chat history,
46
+ class Chatbot:
47
+
48
+ def __init__(self, api_key, index):
49
+ self.index = index
50
+ openai.api_key = api_key
51
+ self.chat_history = []
52
+
53
+ QA_PROMPT_TMPL = (
54
+ "Answer without 'Answer:' word please."
55
+ "you are in a converation with Gochat247's web site visitor\n"
56
+ "user got into this conversation to learn more about Gochat247"
57
+ "you will act like Gochat247 Virtual AI BOT. Be friendy and welcoming\n"
58
+ # "you will be friendy and welcoming\n"
59
+ "The Context of the conversstion should be always limited to learing more about Gochat247 as a company providing Business Process Outosuricng and AI Customer expeeince soltuion /n"
60
+ "The below is the previous chat with the user\n"
61
+ "---------------------\n"
62
+ "{context_str}"
63
+ "\n---------------------\n"
64
+ "Given the context information and the chat history, and not prior knowledge\n"
65
+ "\nanswer the question : {query_str}\n"
66
+ "\n it is ok if you don not know the answer. and ask for infomration \n"
67
+ "Please provide a brief and concise but friendly response."
68
+
69
+
70
+
71
+ )
72
+
73
+ self.QA_PROMPT = QuestionAnswerPrompt(QA_PROMPT_TMPL)
74
+
75
+
76
+ def generate_response(self, user_input):
77
+
78
+ prompt = "\n".join([f"{message['role']}: {message['content']}" for message in self.chat_history[-5:]])
79
+ prompt += f"\nUser: {user_input}"
80
+ self.QA_PROMPT.context_str = prompt
81
+ response = index.query(user_input, text_qa_template=self.QA_PROMPT
82
+ )
83
+
84
+ message = {"role": "assistant", "content": response.response}
85
+ self.chat_history.append({"role": "user", "content": user_input})
86
+ self.chat_history.append(message)
87
+ return message
88
+
89
+ def load_chat_history(self, filename):
90
+ try:
91
+ with open(filename, 'r') as f:
92
+ self.chat_history = json.load(f)
93
+ except FileNotFoundError:
94
+ pass
95
+
96
+ def save_chat_history(self, filename):
97
+ with open(filename, 'w') as f:
98
+ json.dump(self.chat_history, f)
99
+
100
+
101
+ ## Define Chat BOT Class to generate Response , handle chat history,
102
+
103
+ bot = Chatbot("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", index=index)
104
+
105
+
106
+ import gradio as gr
107
+ import time
108
+
109
+
110
+ with gr.Blocks() as demo:
111
+ chatbot = gr.Chatbot(label="GoChat247_Demo")
112
+ msg = gr.Textbox()
113
+ clear = gr.Button("Clear")
114
+
115
+
116
+ def user(user_message, history):
117
+ return "", history + [[user_message, None]]
118
+
119
+ def agent(history):
120
+ last_user_message = history[-1][0]
121
+ agent_message = bot.generate_response(last_user_message)
122
+ history[-1][1] = agent_message ["content"]
123
+ time.sleep(1)
124
+ return history
125
+
126
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
127
+ agent, chatbot, chatbot
128
+ )
129
+ clear.click(lambda: None, None, chatbot, queue=False)
130
+
131
+
132
+
133
+
134
+ if __name__ == "__main__":
135
+ demo.launch()