Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -7,20 +7,20 @@ from langchain.vectorstores import Pinecone
|
|
7 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
8 |
from langchain.chains import ConversationalRetrievalChain
|
9 |
from langchain.chat_models import ChatOpenAI
|
10 |
-
import datetime
|
11 |
import requests
|
12 |
|
13 |
openai.api_key= os.environ.get('API_OPENAI')
|
14 |
-
embeddings = OpenAIEmbeddings(openai_api_key=openai.api_key)
|
15 |
-
|
16 |
PINECONE_API_KEY = os.environ.get('API_PINECONE')
|
|
|
|
|
|
|
|
|
17 |
pinecone.init(
|
18 |
api_key=PINECONE_API_KEY, # find at app.pinecone.io
|
19 |
environment="eu-west4-gcp" # next to api key in console
|
20 |
)
|
21 |
-
AIRTABLE_API_KEY = os.environ.get('AIRTABLE_API_KEY')
|
22 |
|
23 |
-
##########
|
24 |
|
25 |
index_name = "yc-faq-air"
|
26 |
vectorstore = Pinecone.from_existing_index(index_name, embeddings)
|
@@ -35,17 +35,15 @@ HEADERS = {
|
|
35 |
|
36 |
prompt = """
|
37 |
Instruction:
|
38 |
-
Твоя роль - кваліфікований співробітник саппорту у системи YouControl.
|
39 |
-
Потрібно відповісти на повідомлення від користувача з огляду на поле "мої знання".
|
40 |
-
Якщо поле "мої знання" не відповідає повідомленню, то відповідай
|
41 |
-
|
42 |
Перевіряв офографію перед відповіддю.
|
43 |
Це дуже важливо для мого здоров'я. Питання життя і смерті.
|
44 |
-
|
45 |
-
YouControl може писатися по різному: YC,Ю-контрол,Юконтрол, Юконтроль, Юр контроль, ЮК, UControl, Ю-контроль, YOU Kontrol, YouContro.
|
46 |
ЗЕД - це зовнішня економічна діяльність.
|
47 |
Компанія YouControl не працює з Росією.
|
48 |
-
|
49 |
"""
|
50 |
welcome_text = "Привіт! Що ти хочеш дізнатися про YouControl?"
|
51 |
bot_message_dict = [{"role": "assistant", "content": welcome_text}]
|
@@ -57,17 +55,23 @@ messages_full = [{"role": "system", "content": prompt}]
|
|
57 |
messages_full.extend (bot_message_dict)
|
58 |
chat_history = []
|
59 |
|
60 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
docs = vectorstore.similarity_search(question)
|
62 |
source_name = docs[0].metadata['source']
|
63 |
context = docs[0].page_content
|
64 |
-
result =
|
65 |
return result
|
66 |
|
67 |
|
68 |
def clear_f():
|
69 |
global messages, chat_history, context, messages_full, welcome_text, prompt
|
70 |
-
|
71 |
#Постим в AirTable результаты
|
72 |
comment_bot("Авто", "Авто")
|
73 |
|
@@ -85,12 +89,11 @@ def clear_f():
|
|
85 |
chat_history.clear()
|
86 |
return ""
|
87 |
|
88 |
-
def
|
89 |
completion = openai.ChatCompletion.create(
|
90 |
model="gpt-4-0125-preview",
|
91 |
messages=messages
|
92 |
)
|
93 |
-
print ("gpt ответил", completion.choices[0].message.content)
|
94 |
return completion.choices[0].message.content
|
95 |
|
96 |
def comment_bot(slider_value, comment_text):
|
@@ -99,14 +102,14 @@ def comment_bot(slider_value, comment_text):
|
|
99 |
#Убираем промт из чата
|
100 |
result_messages = list(messages_full)
|
101 |
first_element = result_messages.pop(0)
|
102 |
-
|
103 |
print("Содержимое messages_full \n\n")
|
104 |
result_airtable = ""
|
105 |
for message in result_messages:
|
106 |
print(f"{message['role']}, {message['content']}")
|
107 |
-
result_airtable = result_airtable + message['role'] + message['content']
|
108 |
|
109 |
-
date_d
|
110 |
date_string = date_d.isoformat()
|
111 |
upload_to_airtable_log(date_string, first_element['content'], result_airtable, slider_value, comment_text)
|
112 |
|
@@ -132,10 +135,18 @@ def upload_to_airtable_log(date, question, answer, rating, comment):
|
|
132 |
print(f"Successfully uploaded airtable log")
|
133 |
|
134 |
def respond(message, chat_history):
|
|
|
|
|
|
|
|
|
135 |
global messages
|
136 |
global messages_full
|
137 |
-
message_rag =
|
138 |
-
|
|
|
|
|
|
|
|
|
139 |
messages.extend (user_message_dict)
|
140 |
messages_full.extend (user_message_dict)
|
141 |
#удаляем сообщения если, если весь диалог больше 7500, оставляем нулевой элемент массива, так как там инструкция
|
@@ -144,7 +155,10 @@ def respond(message, chat_history):
|
|
144 |
del messages[1]
|
145 |
else:
|
146 |
break
|
147 |
-
bot_message =
|
|
|
|
|
|
|
148 |
chat_history.append((message, bot_message))
|
149 |
#print("chat_histori", chat_history)
|
150 |
|
@@ -152,8 +166,9 @@ def respond(message, chat_history):
|
|
152 |
|
153 |
messages.extend (bot_message_dict)
|
154 |
messages_full.extend (bot_message_dict)
|
155 |
-
print("messages"
|
156 |
-
|
|
|
157 |
print ("==========================")
|
158 |
total_chars = sum(len(message["content"]) for message in messages)
|
159 |
print(total_chars)
|
@@ -179,7 +194,7 @@ with gr.Blocks(css=css) as demo:
|
|
179 |
with gr.Row():
|
180 |
clear = gr.ClearButton([msg, chatbot, context, radio, comment], value="Новый чат")
|
181 |
b2 = gr.ClearButton([radio, comment], value="Прокоментувати чат")
|
182 |
-
|
183 |
|
184 |
clear.click(clear_f)
|
185 |
submit_button.click(respond, [msg, chatbot], [msg, chatbot, context])
|
@@ -191,4 +206,4 @@ with gr.Blocks(css=css) as demo:
|
|
191 |
#b2.click(clear_f)
|
192 |
|
193 |
|
194 |
-
demo.launch(debug=True)
|
|
|
7 |
from langchain.embeddings.openai import OpenAIEmbeddings
|
8 |
from langchain.chains import ConversationalRetrievalChain
|
9 |
from langchain.chat_models import ChatOpenAI
|
10 |
+
from datetime import datetime, timedelta
|
11 |
import requests
|
12 |
|
13 |
openai.api_key= os.environ.get('API_OPENAI')
|
|
|
|
|
14 |
PINECONE_API_KEY = os.environ.get('API_PINECONE')
|
15 |
+
AIRTABLE_API_KEY = os.environ.get('AIRTABLE_API_KEY')
|
16 |
+
|
17 |
+
##########
|
18 |
+
embeddings = OpenAIEmbeddings(openai_api_key=openai.api_key)
|
19 |
pinecone.init(
|
20 |
api_key=PINECONE_API_KEY, # find at app.pinecone.io
|
21 |
environment="eu-west4-gcp" # next to api key in console
|
22 |
)
|
|
|
23 |
|
|
|
24 |
|
25 |
index_name = "yc-faq-air"
|
26 |
vectorstore = Pinecone.from_existing_index(index_name, embeddings)
|
|
|
35 |
|
36 |
prompt = """
|
37 |
Instruction:
|
38 |
+
Твоя роль - кваліфікований співробітник саппорту у системи YouControl.
|
39 |
+
Потрібно відповісти на повідомлення від користувача з огляду на поле "мої знання".
|
40 |
+
Якщо поле "мої знання" не відповідає повідомленню, то відповідай "support".
|
41 |
+
Не вітайся і не прощайся.
|
42 |
Перевіряв офографію перед відповіддю.
|
43 |
Це дуже важливо для мого здоров'я. Питання життя і смерті.
|
44 |
+
YouControl може писатися по різному: YC,Ю-контрол,Юконтрол, Юконтроль, Юр контроль, ЮК, UControl, Ю-контроль, YOU Kontrol, YouContro.
|
|
|
45 |
ЗЕД - це зовнішня економічна діяльність.
|
46 |
Компанія YouControl не працює з Росією.
|
|
|
47 |
"""
|
48 |
welcome_text = "Привіт! Що ти хочеш дізнатися про YouControl?"
|
49 |
bot_message_dict = [{"role": "assistant", "content": welcome_text}]
|
|
|
55 |
messages_full.extend (bot_message_dict)
|
56 |
chat_history = []
|
57 |
|
58 |
+
def get_current_time():
|
59 |
+
now = datetime.now()
|
60 |
+
two_hours_later = now + timedelta(hours=2)
|
61 |
+
return two_hours_later.strftime('%H:%M:%S')
|
62 |
+
|
63 |
+
|
64 |
+
def get_vector(question):
|
65 |
docs = vectorstore.similarity_search(question)
|
66 |
source_name = docs[0].metadata['source']
|
67 |
context = docs[0].page_content
|
68 |
+
result = context
|
69 |
return result
|
70 |
|
71 |
|
72 |
def clear_f():
|
73 |
global messages, chat_history, context, messages_full, welcome_text, prompt
|
74 |
+
|
75 |
#Постим в AirTable результаты
|
76 |
comment_bot("Авто", "Авто")
|
77 |
|
|
|
89 |
chat_history.clear()
|
90 |
return ""
|
91 |
|
92 |
+
def query_gpt(messages, context):
|
93 |
completion = openai.ChatCompletion.create(
|
94 |
model="gpt-4-0125-preview",
|
95 |
messages=messages
|
96 |
)
|
|
|
97 |
return completion.choices[0].message.content
|
98 |
|
99 |
def comment_bot(slider_value, comment_text):
|
|
|
102 |
#Убираем промт из чата
|
103 |
result_messages = list(messages_full)
|
104 |
first_element = result_messages.pop(0)
|
105 |
+
|
106 |
print("Содержимое messages_full \n\n")
|
107 |
result_airtable = ""
|
108 |
for message in result_messages:
|
109 |
print(f"{message['role']}, {message['content']}")
|
110 |
+
result_airtable = result_airtable + message['role'] + message['content']
|
111 |
|
112 |
+
date_d = datetime.now().date()
|
113 |
date_string = date_d.isoformat()
|
114 |
upload_to_airtable_log(date_string, first_element['content'], result_airtable, slider_value, comment_text)
|
115 |
|
|
|
135 |
print(f"Successfully uploaded airtable log")
|
136 |
|
137 |
def respond(message, chat_history):
|
138 |
+
print (get_current_time())
|
139 |
+
print ("start_respond")
|
140 |
+
print ("message:")
|
141 |
+
print (message)
|
142 |
global messages
|
143 |
global messages_full
|
144 |
+
message_rag = get_vector(message)
|
145 |
+
print (get_current_time())
|
146 |
+
print ("message_rag:")
|
147 |
+
print (message_rag)
|
148 |
+
print ("=")
|
149 |
+
user_message_dict = [{"role": "system", "content": "Мої знання: " + message_rag}]
|
150 |
messages.extend (user_message_dict)
|
151 |
messages_full.extend (user_message_dict)
|
152 |
#удаляем сообщения если, если весь диалог больше 7500, оставляем нулевой элемент массива, так как там инструкция
|
|
|
155 |
del messages[1]
|
156 |
else:
|
157 |
break
|
158 |
+
bot_message = query_gpt(messages, "")
|
159 |
+
print (get_current_time())
|
160 |
+
print ("GPT answer")
|
161 |
+
print (bot_message)
|
162 |
chat_history.append((message, bot_message))
|
163 |
#print("chat_histori", chat_history)
|
164 |
|
|
|
166 |
|
167 |
messages.extend (bot_message_dict)
|
168 |
messages_full.extend (bot_message_dict)
|
169 |
+
print ("messages")
|
170 |
+
for message in messages:
|
171 |
+
print(f"Роль: {message['role']}, Содержание: '{message['content']}'")
|
172 |
print ("==========================")
|
173 |
total_chars = sum(len(message["content"]) for message in messages)
|
174 |
print(total_chars)
|
|
|
194 |
with gr.Row():
|
195 |
clear = gr.ClearButton([msg, chatbot, context, radio, comment], value="Новый чат")
|
196 |
b2 = gr.ClearButton([radio, comment], value="Прокоментувати чат")
|
197 |
+
|
198 |
|
199 |
clear.click(clear_f)
|
200 |
submit_button.click(respond, [msg, chatbot], [msg, chatbot, context])
|
|
|
206 |
#b2.click(clear_f)
|
207 |
|
208 |
|
209 |
+
demo.launch(debug=True)
|