-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
196 lines (165 loc) · 6.19 KB
/
app.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
import os
import openai
from dotenv import load_dotenv
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_bolt import App, Ack, Respond
from slack_sdk import WebClient
from slack_bolt.adapter.flask import SlackRequestHandler
from langchain.tools import DuckDuckGoSearchRun
from hugchat import hugchat
import sqlite3
load_dotenv()
SLACK_BOT_TOKEN = os.getenv('SLACK_BOT_TOKEN')
SLACK_APP_TOKEN = os.getenv('SLACK_APP_TOKEN')
openai.api_key = os.getenv('OPENAI_API_TOKEN')
OPENAI_MODEL = os.getenv('OPENAI_MODEL')
# Initializes your app with your bot token and socket mode handler
app = App(token=SLACK_BOT_TOKEN)
search = DuckDuckGoSearchRun()
db = "chatgptomatic.db"
chatGPTPrompt = "The following is a conversation with an AI assistant. The assistant is helpful, creative, clever and very friendly. Use the conversation history to respond to the user"
def ddgSearch(question):
try:
result = search.run(question)
except:
result = ""
return result
def moderate(input):
response = openai.Moderation.create(
input=input,
)
return response.results[0].flagged
def clear_history(user):
messages = []
global has_run
if has_run == True:
messages = messages
else:
clearConversation(user)
messages = []
role = "system"
content = chatGPTPrompt
messages = [ {"role": role, "content": content} ]
updateConversation(user, role, content)
has_run = True
def updateConversation(user, role, content):
connection = sqlite3.connect(db)
cursor = connection.cursor()
cursor.execute("INSERT INTO conversations (user, role, content) VALUES (?,?,?)", (user, role, content))
connection.commit()
def clearConversation(user):
connection = sqlite3.connect(db)
cursor = connection.cursor()
cursor.execute("delete from conversations where user = ?", (user,))
connection.commit()
role = "system"
content = chatGPTPrompt
connection = sqlite3.connect(db)
cursor = connection.cursor()
cursor.execute("Insert into conversations (user, role, content) values (?,?,?)", (user, role, content))
connection.commit()
def importConversation(user, messages):
connection = sqlite3.connect(db)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute("select * from conversations where user = ?", (user,))
exist = cursor.fetchone()
if exit is not None:
for row in cursor:
messages.append({"role": row['role'], "content": row['content']})
else:
connection = sqlite3.connect(db)
cursor = connection.cursor()
cursor.execute("Insert into conversations (user, role, content) values (?,?,?)", (user, "system", chatGPTPrompt))
connection.commit()
connection = sqlite3.connect(db)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute("select * from conversations where user = ?", (user,))
for row in cursor:
messages.append({"role": row['role'], "content": row['content']})
#Message handler for Slack
@app.message(".*")
def message_handler(message, say, logger):
messages = []
importConversation(message['user'], messages)
response = ""
flagged = moderate(message['text'])
if flagged == False:
updateConversation(message['user'],"user", message['text'])
messages.append(
{"role": "user", "content": message['text']},
)
chat = openai.ChatCompletion.create(
model=OPENAI_MODEL, messages=messages
)
response = chat.choices[0].message
output = chat.choices[0].message.content
flagged = moderate(output)
if flagged == False:
output = output
updateConversation(message['user'], "assistant", output)
else:
output = "Response flagged by OpenAI moderation."
say(OPENAI_MODEL + ": " + message['text'] + " " + output)
@app.command("/askgpt")
def askgpt_submit(ack: Ack, respond: Respond, command: dict, client: WebClient):
ack() # acknowledge command request
messages = []
messages = [ {"role": "system", "content": "You are in intelligent assistant. Read the following passage and answer the question at the end."} ]
response = ""
searchResult = ""
flagged = moderate(command['text'])
if flagged == False:
searchResult = ddgSearch(command['text'])
messages.append(
{"role": "user", "content": searchResult + " " + command['text']},
)
chat = openai.ChatCompletion.create(
model=OPENAI_MODEL, messages=messages
)
response = chat.choices[0].message
output = chat.choices[0].message.content
flagged = moderate(output)
if flagged == False:
output = output
else:
output = "Response flagged by OpenAI moderation."
else:
output = "Question flagged by OpenAI moderation."
respond(text="AskGPT: " + command['text'] + " " + output)
return
@app.command("/askhc")
def askhc_submit(ack: Ack, respond: Respond, command: dict, client: WebClient):
ack() # acknowledge command request
searchResult = ddgSearch(command['text'])
instructions = "You are an intelligent assistant. Read the following passage and answer the question at the end."
chatbot = hugchat.ChatBot()
hcTemp = 0.1
try:
output = chatbot.chat(command['text'], hcTemp)
print(output)
except:
output = "Hugging Chat is busy try again."
respond(text="AskHC: " + command['text'] + " " + output)
return
@app.command("/clearconversation")
def clearconversation_submit(ack: Ack, respond: Respond, command: dict, client: WebClient):
ack() # acknowledge command request
clearConversation(command['user_id'])
respond(text="Chat History Cleared")
return
# Start your app
if __name__ == "__main__":
SocketModeHandler(app, SLACK_APP_TOKEN).start()
# Attach the slack_bolt app to a flask app handler
#from flask import Flask, request
#flask_app = Flask(__name__)
#handler = SlackRequestHandler(app)
#@flask_app.route("/slack/events", methods=["POST"])
#def slack_events():
# return handler.handle(request)
# Start your app
#if __name__ == "__main__":
# app.start(port=int(os.environ.get("PORT", 3000)))