Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -23,9 +23,17 @@ AIRTABLE_API_KEY = os.environ.get('API_PINECONE')
|
|
23 |
index_name = "yc-faq-air"
|
24 |
vectorstore = Pinecone.from_existing_index(index_name, embeddings)
|
25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
prompt = "Instruction: Твоя роль - кваліфікований співробітник саппорту у системи YouControl. Потрібно відповісти на питання від користувача з огляду на контекст. Контекст ми беремо з бази знань, але вона може бути не повна. Якщо контекст не коректний, то відповідай на свій розсуд або передай запит сапорту, про контекс нічого не пишемо у відповіді. YouControl може писатися по різному: YC,Ю-контрол,Юконтрол, Юконтроль, Юр контроль, ЮК, UControl, Ю-контроль, YOU Kontrol, YouContro. ЗЕД - це зовнішня економічна діяльність."+"""
|
28 |
"""
|
|
|
29 |
messages = [{"role": "system", "content": prompt}]
|
30 |
chat_history = []
|
31 |
|
@@ -33,17 +41,24 @@ def ask_yc_bot(question):
|
|
33 |
docs = vectorstore.similarity_search(question)
|
34 |
source_name = docs[0].metadata['source']
|
35 |
context = docs[0].page_content
|
36 |
-
result = "
|
37 |
return result
|
38 |
|
39 |
|
40 |
def clear_f():
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
"""
|
44 |
messages = []
|
45 |
messages = [{"role": "system", "content": prompt}]
|
46 |
-
print("")
|
47 |
chat_history.clear()
|
48 |
return ""
|
49 |
|
@@ -52,13 +67,50 @@ def query_gpt_3_5(messages, context):
|
|
52 |
model="gpt-4-0613",
|
53 |
messages=messages
|
54 |
)
|
|
|
55 |
return completion.choices[0].message.content
|
56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
def respond(message, chat_history):
|
|
|
59 |
message_rag = ask_yc_bot(message)
|
60 |
user_message_dict = [{"role": "user", "content": message_rag}]
|
61 |
messages.extend (user_message_dict)
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
bot_message = query_gpt_3_5(messages, "")
|
63 |
chat_history.append((message, bot_message))
|
64 |
#print("chat_histori", chat_history)
|
@@ -68,29 +120,42 @@ def respond(message, chat_history):
|
|
68 |
messages.extend (bot_message_dict)
|
69 |
print("messages", messages)
|
70 |
print ("message_rag=", message_rag)
|
|
|
|
|
|
|
71 |
return "", chat_history, message_rag
|
72 |
css = """
|
73 |
footer{display:none !important}
|
74 |
-
.custom-button {
|
75 |
-
height: 83px;
|
76 |
-
}
|
77 |
"""
|
78 |
|
|
|
79 |
with gr.Blocks(css=css) as demo:
|
80 |
with gr.Row():
|
81 |
with gr.Column(scale=2):
|
82 |
chatbot = gr.Chatbot([(None, "Привіт! Що ти хочеш дізнатися про YouControl?")], height=300)
|
83 |
with gr.Column(scale=1):
|
84 |
context = gr.Textbox(lines=11, label="Last Context")
|
|
|
85 |
with gr.Row():
|
86 |
with gr.Column(scale=2):
|
87 |
-
|
88 |
with gr.Column(scale=1):
|
89 |
-
|
90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
clear.click(clear_f)
|
92 |
submit_button.click(respond, [msg, chatbot], [msg, chatbot, context])
|
93 |
msg.submit(respond, [msg, chatbot], [msg, chatbot, context])
|
94 |
|
|
|
|
|
|
|
|
|
95 |
|
96 |
demo.launch(debug=True)
|
|
|
23 |
index_name = "yc-faq-air"
|
24 |
vectorstore = Pinecone.from_existing_index(index_name, embeddings)
|
25 |
|
26 |
+
AIRTABLE_ENDPOINT = "https://api.airtable.com/v0/appv2hF1PzrseVdeW/data_m"
|
27 |
+
AIRTABLE_ENDPOINT_LOG = "https://api.airtable.com/v0/appv2hF1PzrseVdeW/log_chat"
|
28 |
+
HEADERS = {
|
29 |
+
"Authorization": f"Bearer {AIRTABLE_API_KEY}",
|
30 |
+
"Content-Type": "application/json"
|
31 |
+
}
|
32 |
+
|
33 |
|
34 |
prompt = "Instruction: Твоя роль - кваліфікований співробітник саппорту у системи YouControl. Потрібно відповісти на питання від користувача з огляду на контекст. Контекст ми беремо з бази знань, але вона може бути не повна. Якщо контекст не коректний, то відповідай на свій розсуд або передай запит сапорту, про контекс нічого не пишемо у відповіді. YouControl може писатися по різному: YC,Ю-контрол,Юконтрол, Юконтроль, Юр контроль, ЮК, UControl, Ю-контроль, YOU Kontrol, YouContro. ЗЕД - це зовнішня економічна діяльність."+"""
|
35 |
"""
|
36 |
+
|
37 |
messages = [{"role": "system", "content": prompt}]
|
38 |
chat_history = []
|
39 |
|
|
|
41 |
docs = vectorstore.similarity_search(question)
|
42 |
source_name = docs[0].metadata['source']
|
43 |
context = docs[0].page_content
|
44 |
+
result = "Question: " + question + "\n\n" + " Context: " + context
|
45 |
return result
|
46 |
|
47 |
|
48 |
def clear_f():
|
49 |
+
|
50 |
+
global messages, chat_history, context
|
51 |
+
context=""
|
52 |
+
prompt = """
|
53 |
+
Instruction: Твоя роль - кваліфікований співробітник саппорту у системи YouControl.
|
54 |
+
Потрібно відповісти на питання від користувача з огляду на контекст.
|
55 |
+
Контекст ми беремо з бази знань, але вона може бути не повна.
|
56 |
+
Якщо контекст не коректний, то відповідай на свій розсуд або передай запит сапорту, про контекс нічого не пишемо у відповіді.
|
57 |
+
YouControl може писатися по різному: YC,Ю-контрол,Юконтрол, Юконтроль, Юр контроль, ЮК, UControl, Ю-контроль, YOU Kontrol, YouContro.
|
58 |
+
ЗЕД - це зовнішня економічна діяльність
|
59 |
"""
|
60 |
messages = []
|
61 |
messages = [{"role": "system", "content": prompt}]
|
|
|
62 |
chat_history.clear()
|
63 |
return ""
|
64 |
|
|
|
67 |
model="gpt-4-0613",
|
68 |
messages=messages
|
69 |
)
|
70 |
+
print ("gpt ответил", completion.choices[0].message.content)
|
71 |
return completion.choices[0].message.content
|
72 |
|
73 |
+
def comment_bot(slider_value, comment_text):
|
74 |
+
global messages
|
75 |
+
print ("Длина messages:", len(messages))
|
76 |
+
result = '\n'.join(message['content'] for message in messages)
|
77 |
+
print ("result:", result)
|
78 |
+
date_d = datetime.datetime.now().date()
|
79 |
+
date_string = date_d.isoformat()
|
80 |
+
upload_to_airtable_log(date_string, "-", result, slider_value, comment_text)
|
81 |
+
|
82 |
+
return "" # Если функция должна что-то возвращать, замените это на нужный вывод
|
83 |
+
|
84 |
+
def upload_to_airtable_log(date, question, answer, rating, comment):
|
85 |
+
data = {
|
86 |
+
"records": [{
|
87 |
+
"fields": {
|
88 |
+
"date": date,
|
89 |
+
"question": question,
|
90 |
+
"answer": answer,
|
91 |
+
"rating": rating,
|
92 |
+
"comment": comment
|
93 |
+
}
|
94 |
+
}]
|
95 |
+
}
|
96 |
+
response = requests.post(AIRTABLE_ENDPOINT_LOG, headers=HEADERS, json=data)
|
97 |
+
|
98 |
+
if response.status_code != 200:
|
99 |
+
print(f"Error uploading airtable (log ) Status code: {response.status_code}. Content: {response.content}")
|
100 |
+
else:
|
101 |
+
print(f"Successfully uploaded airtable log")
|
102 |
|
103 |
def respond(message, chat_history):
|
104 |
+
global messages
|
105 |
message_rag = ask_yc_bot(message)
|
106 |
user_message_dict = [{"role": "user", "content": message_rag}]
|
107 |
messages.extend (user_message_dict)
|
108 |
+
#удаляем сообщения если, если весь диалог больше 7500, оставляем нулевой элемент массива, так как там инструкция
|
109 |
+
while sum(len(message["content"]) for message in messages) >= 7500:
|
110 |
+
if len(messages) > 1:
|
111 |
+
del messages[1]
|
112 |
+
else:
|
113 |
+
break
|
114 |
bot_message = query_gpt_3_5(messages, "")
|
115 |
chat_history.append((message, bot_message))
|
116 |
#print("chat_histori", chat_history)
|
|
|
120 |
messages.extend (bot_message_dict)
|
121 |
print("messages", messages)
|
122 |
print ("message_rag=", message_rag)
|
123 |
+
print ("==========================")
|
124 |
+
total_chars = sum(len(message["content"]) for message in messages)
|
125 |
+
print(total_chars)
|
126 |
return "", chat_history, message_rag
|
127 |
css = """
|
128 |
footer{display:none !important}
|
|
|
|
|
|
|
129 |
"""
|
130 |
|
131 |
+
|
132 |
with gr.Blocks(css=css) as demo:
|
133 |
with gr.Row():
|
134 |
with gr.Column(scale=2):
|
135 |
chatbot = gr.Chatbot([(None, "Привіт! Що ти хочеш дізнатися про YouControl?")], height=300)
|
136 |
with gr.Column(scale=1):
|
137 |
context = gr.Textbox(lines=11, label="Last Context")
|
138 |
+
msg = gr.Textbox(label="", placeholder="Введите сообщение")
|
139 |
with gr.Row():
|
140 |
with gr.Column(scale=2):
|
141 |
+
submit_button = gr.Button("Отправить")
|
142 |
with gr.Column(scale=1):
|
143 |
+
clear = gr.ClearButton([msg, chatbot, context], value="Новый чат")
|
144 |
+
|
145 |
+
|
146 |
+
with gr.Row():
|
147 |
+
radio = gr.Radio(label="Рейтинг відповіді", choices=["Нема", "1", "2", "3", "4", "5"], value="Нема")
|
148 |
+
comment = gr.Textbox(lines=2, label = "Коментар")
|
149 |
+
with gr.Row():
|
150 |
+
b2 = gr.ClearButton([radio, comment], value="Прокоментувати чат")
|
151 |
+
|
152 |
clear.click(clear_f)
|
153 |
submit_button.click(respond, [msg, chatbot], [msg, chatbot, context])
|
154 |
msg.submit(respond, [msg, chatbot], [msg, chatbot, context])
|
155 |
|
156 |
+
inp_2 = [radio, comment]
|
157 |
+
b2.click(comment_bot, inputs=inp_2, outputs=comment)
|
158 |
+
#b2.click(clear_f)
|
159 |
+
|
160 |
|
161 |
demo.launch(debug=True)
|