-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
303 lines (222 loc) · 8.55 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import os
import asyncio
import requests
import logging
import requests
import validators
from threading import Thread
from flask import Flask
from flask import request, jsonify, make_response
from bs4 import BeautifulSoup as bs4
from slack_sdk import WebClient
import slack
from slackeventsapi import SlackEventAdapter
from slack_sdk.errors import SlackApiError
from langchain_community.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
MessagesPlaceholder,
HumanMessagePromptTemplate,
SystemMessagePromptTemplate,
)
from langchain.schema import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory
app = Flask(__name__)
# Set up logging
logging.basicConfig(level=logging.WARNING)
logging.getLogger('httpx').setLevel(logging.WARNING)
logging.getLogger('openai').setLevel(logging.WARNING)
slack_token = os.environ.get('SLACK_BOT_TOKEN')
slack_client_id = os.environ.get('SLACK_CLIENT_ID')
SLACK_SIGNING_SECRET = os.environ["SLACK_SIGNING_SECRET"]
SLACK_CLIENT_SECRET = os.environ["SLACK_CLIENT_SECRET"]
slack_events_adapter = SlackEventAdapter(SLACK_SIGNING_SECRET, "/slack/events", app)
client = WebClient(token=slack_token)
user_db = {}
app_opened_tracker = {}
token_database = {}
cached_link_sumarries = {}
llm = ChatOpenAI(temperature=0, model_name="gpt-4-0125-preview")
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
def start_command_worker(loop):
"""Switch to new event loop and run forever"""
asyncio.set_event_loop(loop)
loop.run_forever()
command_loop = asyncio.new_event_loop()
command_worker = Thread(target=start_command_worker, args=(command_loop,))
command_worker.start()
# tools
function_dscrp = [
]
@app.route("/")
def home():
print(request)
auth_code = request.args["code"]
logging.info("Recieved auth code for oauth from slack: ", auth_code)
print(auth_code)
global client
response = client.oauth_v2_access(
client_id=slack_client_id,
client_secret=SLACK_CLIENT_SECRET,
code=auth_code
)
logging.info("Exchanged Auth Code for Oauth V2 Access", response)
# save team id with corresponding auth access token to a database!
# dummy representation of a database for now
teamID = response["team"]["id"]
token_database[teamID] = response["access_token"]
logging.info("Team ID & Coressponding Bot Token Saved to Temporary DB", token_database)
return "Authorization Succesful. Check out HawaGPT in your Slack Workspace!"
@app.route("/hawagpt", methods=['GET', 'POST'])
def get_slash_command():
logging.info("HawaGPT Slack Command Invoked")
command_loop.call_soon_threadsafe(respond_to_slack_message,
request.form)
return jsonify(
response_type='ephemeral',
text="Getting your answer... to the question: " + request.form['text'],
)
@app.route("/gibbs", methods=['GET', 'POST'])
def validate_url():
res = request.form
page = ""
url_link =res['text']
URL = ""
if(validators.url(url_link)):
URL = url_link
if(URL == ""):
return jsonify(response_type="ephemeral", text="Invalid URL Format. Please try again with a valid URL")
if(url_link in cached_link_sumarries):
answer = cached_link_sumarries[url_link]
return jsonify(
response_type='in_channel',
text=f"🔗 {url_link} \n \n {answer} \n\nSummary brought to you by Gibbs™ (Copyright © 2024 Madrona Venture Labs and IGBB Productions. All Rights Reserved.)",
)
page = requests.get(URL)
command_loop.call_soon_threadsafe(scrape_and_summarize, url_link,
page, res['response_url'])
return jsonify(
response_type='ephemeral',
text="Summarizing Link... " + request.form['text'],
)
def scrape_and_summarize(link, page, response_url):
page_contents = page.content
soup = bs4(page_contents, "html.parser")
body = soup.find("body").text.strip()
# 'p, pre, article, blockquote, h1, h2, h3, h4, h5, h6' and maybe 'li'
max_length = 8192
#truncated_body = body[:max_length]
# return raw text or summary (flag)
prompt = ChatPromptTemplate(
messages=[
SystemMessagePromptTemplate.from_template(
"""Extract the key 3-4 main ideas from this document, including what would be useful to know from it. Keep your response to a short paragraph with 3-4 sentences.
If you don't know an answer, you say I dont know!
"""
),
HumanMessagePromptTemplate.from_template("{question}")
]
)
memory = ConversationBufferMemory()
conversation = LLMChain(
llm=llm,
prompt=prompt,
verbose=True,
memory=memory
)
answer = conversation({"question": body})['text']
data = {
'response_type': 'in_channel',
'text': f"🔗 {link} \n \n {answer} \n\nSummary brought to you by Gibbs™ (Copyright © 2024 Madrona Venture Labs and IGBB Productions. All Rights Reserved.)"
}
requests.post(response_url, json=data)
cached_link_sumarries[link] = answer
def respond_to_slack_message(res):
logging.info("Slack Slash Command Event", res)
user_input = res['text']
channel_id = res['channel_id']
user_id = res['user_id']
logging.info(f"Question asked by User: + {user_id} + in channel {channel_id}")
prompt = ChatPromptTemplate(
messages=[
SystemMessagePromptTemplate.from_template(
"""You are a nice chatbot having a conversation with a human. You are a helpful assistant able to assist with a wide variety of tasks!
If you don't know an answer, you say I dont know!
"""
),
MessagesPlaceholder(variable_name="chat_history"),
HumanMessagePromptTemplate.from_template("{question}")
]
)
logging.info("Prompting Started")
if user_id not in user_db:
user_db[user_id] = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
logging.info("New conversation memory buffer created for {user_id}")
curr_memory = user_db.get(user_id)
logging.info(f"Conversation Memory for user: {user_id}", curr_memory.load_memory_variables({}))
logging.info("Creating LLMChain...")
conversation = LLMChain(
llm=llm,
prompt=prompt,
verbose=True,
memory=curr_memory
)
answer = conversation({"question": user_input})['text']
logging.info("Answer Received")
curr_at = res['user_id']
data = {
'response_type': 'ephemeral',
'text': f"<@{curr_at}> \n" + answer
}
requests.post(res['response_url'], json=data)
logging.info("Response Posted to Slack!")
# client.chat_postMessage(
# channel=channel_id,
# text=(f"<@{curr_at}> \n 🤓 Query: " + res['text'] + "\n\n🧠 Answer: " + answer) )
#
return make_response("", 200)
@slack_events_adapter.on("app_home_opened")
def home_tab_opened(data):
logging.info("app_home_opened slack event! ", data)
print(data)
user_id = data["event"]["user"]
if(user_id not in app_opened_tracker):
client.chat_postMessage(
text="Welcome to HawaGPT! You can use the slash command /hawagpt to get your questions answered & /gibbs to get link summaries!",
channel=data['event']['channel'],
)
app_opened_tracker[user_id] = True
# @slack_events_adapter.on("message")
# def message(event_data):
# print("message detected!")
# print(event_data)
# page = ""
# url_link = ""
# URL = ""
# if(validators.url(url_link)):
# URL = url_link
# print("url valid")
# else:
# return
# page = requests.get(url_link)
# scrape_and_summarize_2(url_link, page.content, event_data)
# print("called method?")
# def scrape_and_summarize_2(link, contents, event_data):
# print("scraping...")
# @staticmethod
# @slack_events_adapter.on("app_mention")
# def app_mentioned(data):
# logging.info("app_mention slack event! ", data)
# user = data['event']['user']
# channel_id=data['event']['channel']
# responseText = (f'hi <@{user}>')
# response =client.chat_postMessage(
# channel=channel_id,
# user_id = user,
# user = user,
# text = responseText
# )
if __name__ == "__main__":
app.run(port=8080)