-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
145 lines (110 loc) · 3.93 KB
/
main.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
import os
import re
import structlog
from dotenv import load_dotenv
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_bolt.context.say import Say
from chai import Chai
from memory import Memory
load_dotenv()
logger = structlog.get_logger()
app = App(token=os.environ.get("SLACK_BOT_TOKEN"))
memory = Memory()
chai = Chai()
def init_user_profile(user_id: str) -> dict:
"""
Initialize user profile
:param user_id: User ID
"""
user_profile = memory.get_profile(user_id)
logger.debug(
"Initializing user profile", user_id=user_id, user_profile=user_profile
)
if not user_profile:
user_profile = app.client.users_profile_get(user=user_id).get("profile", {})
team_info = app.client.team_info().get("team", None)
user_profile["team"] = team_info
memory.set_profile(user_id, user_profile)
logger.debug("User profile initialized", user_profile=user_profile)
return user_profile
def get_chat_id(event) -> tuple[str, str]:
"""
Get chat ID from event
:param event: Slack event
:return: Chat ID and thread ID
"""
uid = event["channel"]
thread = event.get("thread_ts", event.get("ts"))
chat_id = f"{uid}_{thread}"
return chat_id, thread
def append_system_message(messages_history: list, user_profile: dict) -> list:
"""
Append system message to the beginning of the history
:param messages_history: Messages history
:param user_profile: User profile
:return: Messages history
"""
use_profile = os.environ.get("USE_USER_PROFILE", "true").lower() == "true"
system_message = os.environ.get("SYSTEM_MESSAGE", "")
if use_profile:
messages_history.insert(
0,
{
"role": "system",
"content": f"{system_message}\n\nUser profile:\nName: {user_profile['real_name']} | Title: {user_profile['title']} | Company: {user_profile['team']['name']}",
},
)
else:
messages_history.insert(
0,
{
"role": "system",
"content": f"{system_message}\n\nUser profile:\nName: {user_profile['real_name']} | Title: {user_profile['title']} | Company: {user_profile['team']['name']}",
},
)
return messages_history
@app.event("message")
def process_message(event, say: Say):
"""
Process message
This process is triggered when a user sends a message to the bot
through a direct message or a thread.
Bot replies inside the thread. If the user sends a message to the bot
outside a thread, the bot will create a new thread and reply there.
:param event: Slack event
:param say: Say
"""
user_id = event["user"]
chat_id, thread = get_chat_id(event)
user_profile = init_user_profile(user_id)
message = event.get("text", "")
message = re.sub("<@.*?> ", "", message, flags=re.IGNORECASE)
memory.add_message(chat_id, {"role": "user", "content": message})
messages_history = memory.get_messages(chat_id)
logger.debug(
"Processing message",
chat_id=chat_id,
message=message,
messages_history=messages_history,
)
messages_history = append_system_message(messages_history, user_profile)
response = chai.completion(
messages=[
{
"role": message["role"],
"content": message["content"],
}
for message in messages_history
],
user_id=user_id,
)
if len(response["choices"]) > 0:
response = response["choices"][0]["message"]["content"]
else:
logger.error("No response from model", chat_id=chat_id, response=response)
response = ""
memory.add_message(chat_id, {"role": "assistant", "content": response})
say(response, thread_ts=thread)
if __name__ == "__main__":
SocketModeHandler(app, os.environ.get("SLACK_APP_TOKEN")).start()