gptbot.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import os
  2. import inspect
  3. import logging
  4. import signal
  5. import random
  6. import uuid
  7. import openai
  8. import asyncio
  9. import markdown2
  10. import tiktoken
  11. import duckdb
  12. from nio import AsyncClient, RoomMessageText, MatrixRoom, Event, InviteEvent, AsyncClientConfig, MegolmEvent, GroupEncryptionError, EncryptionError, HttpClient, Api
  13. from nio.api import MessageDirection
  14. from nio.responses import RoomMessagesError, SyncResponse, RoomRedactError, WhoamiResponse, JoinResponse, RoomSendResponse
  15. from nio.crypto import Olm
  16. from configparser import ConfigParser
  17. from datetime import datetime
  18. from argparse import ArgumentParser
  19. from typing import List, Dict, Union, Optional
  20. from commands import COMMANDS
  21. from classes import DuckDBStore
  22. def logging(message: str, log_level: str = "info"):
  23. caller = inspect.currentframe().f_back.f_code.co_name
  24. timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S:%f")
  25. print(f"[{timestamp}] - {caller} - [{log_level.upper()}] {message}")
  26. CONTEXT = {
  27. "database": False,
  28. "default_room_name": "GPTBot",
  29. "system_message": "You are a helpful assistant.",
  30. "max_tokens": 3000,
  31. "max_messages": 20,
  32. "model": "gpt-3.5-turbo",
  33. "client": None,
  34. "sync_token": None,
  35. "logger": logging
  36. }
  37. async def gpt_query(messages: list, model: Optional[str] = None):
  38. model = model or CONTEXT["model"]
  39. logging(f"Querying GPT with {len(messages)} messages")
  40. try:
  41. response = openai.ChatCompletion.create(
  42. model=model,
  43. messages=messages
  44. )
  45. result_text = response.choices[0].message['content']
  46. tokens_used = response.usage["total_tokens"]
  47. logging(f"Used {tokens_used} tokens")
  48. return result_text, tokens_used
  49. except Exception as e:
  50. logging(f"Error during GPT API call: {e}", "error")
  51. return None, 0
  52. async def fetch_last_n_messages(room_id: str, n: Optional[int] = None,
  53. client: Optional[AsyncClient] = None, sync_token: Optional[str] = None):
  54. messages = []
  55. n = n or CONTEXT["max_messages"]
  56. client = client or CONTEXT["client"]
  57. sync_token = sync_token or CONTEXT["sync_token"]
  58. logging(
  59. f"Fetching last {2*n} messages from room {room_id} (starting at {sync_token})...")
  60. response = await client.room_messages(
  61. room_id=room_id,
  62. start=sync_token,
  63. limit=2*n,
  64. )
  65. if isinstance(response, RoomMessagesError):
  66. logging(
  67. f"Error fetching messages: {response.message} (status code {response.status_code})", "error")
  68. return []
  69. for event in response.chunk:
  70. if len(messages) >= n:
  71. break
  72. if isinstance(event, MegolmEvent):
  73. try:
  74. event = await client.decrypt_event(event)
  75. except (GroupEncryptionError, EncryptionError):
  76. logging(
  77. f"Could not decrypt message {event.event_id} in room {room_id}", "error")
  78. continue
  79. if isinstance(event, RoomMessageText):
  80. if event.body.startswith("!gptbot ignoreolder"):
  81. break
  82. if not event.body.startswith("!"):
  83. messages.append(event)
  84. logging(f"Found {len(messages)} messages (limit: {n})")
  85. # Reverse the list so that messages are in chronological order
  86. return messages[::-1]
  87. def truncate_messages_to_fit_tokens(messages: list, max_tokens: Optional[int] = None,
  88. model: Optional[str] = None, system_message: Optional[str] = None):
  89. max_tokens = max_tokens or CONTEXT["max_tokens"]
  90. model = model or CONTEXT["model"]
  91. system_message = system_message or CONTEXT["system_message"]
  92. encoding = tiktoken.encoding_for_model(model)
  93. total_tokens = 0
  94. system_message_tokens = len(encoding.encode(system_message)) + 1
  95. if system_message_tokens > max_tokens:
  96. logging(
  97. f"System message is too long to fit within token limit ({system_message_tokens} tokens) - cannot proceed", "error")
  98. return []
  99. total_tokens += system_message_tokens
  100. total_tokens = len(system_message) + 1
  101. truncated_messages = []
  102. for message in [messages[0]] + list(reversed(messages[1:])):
  103. content = message["content"]
  104. tokens = len(encoding.encode(content)) + 1
  105. if total_tokens + tokens > max_tokens:
  106. break
  107. total_tokens += tokens
  108. truncated_messages.append(message)
  109. return [truncated_messages[0]] + list(reversed(truncated_messages[1:]))
  110. async def process_query(room: MatrixRoom, event: RoomMessageText, **kwargs):
  111. client = kwargs.get("client") or CONTEXT["client"]
  112. database = kwargs.get("database") or CONTEXT["database"]
  113. system_message = kwargs.get("system_message") or CONTEXT["system_message"]
  114. max_tokens = kwargs.get("max_tokens") or CONTEXT["max_tokens"]
  115. await client.room_typing(room.room_id, True)
  116. await client.room_read_markers(room.room_id, event.event_id)
  117. last_messages = await fetch_last_n_messages(room.room_id, 20)
  118. chat_messages = [{"role": "system", "content": system_message}]
  119. for message in last_messages:
  120. role = "assistant" if message.sender == client.user_id else "user"
  121. if not message.event_id == event.event_id:
  122. chat_messages.append({"role": role, "content": message.body})
  123. chat_messages.append({"role": "user", "content": event.body})
  124. # Truncate messages to fit within the token limit
  125. truncated_messages = truncate_messages_to_fit_tokens(
  126. chat_messages, max_tokens - 1)
  127. response, tokens_used = await gpt_query(truncated_messages)
  128. if response:
  129. logging(f"Sending response to room {room.room_id}...")
  130. # Convert markdown to HTML
  131. message = await send_message(room, response)
  132. if database:
  133. logging("Logging tokens used...")
  134. with database.cursor() as cursor:
  135. cursor.execute(
  136. "INSERT INTO token_usage (message_id, room_id, tokens, timestamp) VALUES (?, ?, ?, ?)",
  137. (message.event_id, room.room_id, tokens_used, datetime.now()))
  138. database.commit()
  139. else:
  140. # Send a notice to the room if there was an error
  141. logging("Error during GPT API call - sending notice to room")
  142. send_message(
  143. room, "Sorry, I'm having trouble connecting to the GPT API right now. Please try again later.", True)
  144. print("No response from GPT API")
  145. await client.room_typing(room.room_id, False)
  146. async def process_command(room: MatrixRoom, event: RoomMessageText, context: Optional[dict] = None):
  147. context = context or CONTEXT
  148. logging(
  149. f"Received command {event.body} from {event.sender} in room {room.room_id}")
  150. command = event.body.split()[1] if event.body.split()[1:] else None
  151. message = await COMMANDS.get(command, COMMANDS[None])(room, event, context)
  152. if message:
  153. room_id, event, content = message
  154. await send_message(context["client"].rooms[room_id], content["body"],
  155. True if content["msgtype"] == "m.notice" else False, context["client"])
  156. async def message_callback(room: MatrixRoom, event: RoomMessageText | MegolmEvent, **kwargs):
  157. context = kwargs.get("context") or CONTEXT
  158. logging(f"Received message from {event.sender} in room {room.room_id}")
  159. if isinstance(event, MegolmEvent):
  160. try:
  161. event = await context["client"].decrypt_event(event)
  162. except Exception as e:
  163. try:
  164. logging("Requesting new encryption keys...")
  165. await context["client"].request_room_key(event)
  166. except:
  167. pass
  168. logging(f"Error decrypting message: {e}", "error")
  169. await send_message(room, "Sorry, I couldn't decrypt that message. Please try again later or switch to a room without encryption.", True, context["client"])
  170. return
  171. if event.sender == context["client"].user_id:
  172. logging("Message is from bot itself - ignoring")
  173. elif event.body.startswith("!gptbot"):
  174. await process_command(room, event)
  175. elif event.body.startswith("!"):
  176. logging("Might be a command, but not for this bot - ignoring")
  177. else:
  178. await process_query(room, event, context=context)
  179. async def room_invite_callback(room: MatrixRoom, event: InviteEvent, **kwargs):
  180. client: AsyncClient = kwargs.get("client") or CONTEXT["client"]
  181. if room.room_id in client.rooms:
  182. logging(f"Already in room {room.room_id} - ignoring invite")
  183. return
  184. logging(f"Received invite to room {room.room_id} - joining...")
  185. response = await client.join(room.room_id)
  186. if isinstance(response, JoinResponse):
  187. await send_message(room, "Hello! I'm a helpful assistant. How can I help you today?", client)
  188. else:
  189. logging(f"Error joining room {room.room_id}: {response}", "error")
  190. async def send_message(room: MatrixRoom, message: str, notice: bool = False, client: Optional[AsyncClient] = None):
  191. client = client or CONTEXT["client"]
  192. markdowner = markdown2.Markdown(extras=["fenced-code-blocks"])
  193. formatted_body = markdowner.convert(message)
  194. msgtype = "m.notice" if notice else "m.text"
  195. msgcontent = {"msgtype": msgtype, "body": message,
  196. "format": "org.matrix.custom.html", "formatted_body": formatted_body}
  197. content = None
  198. if client.olm and room.encrypted:
  199. try:
  200. if not room.members_synced:
  201. responses = []
  202. responses.append(await client.joined_members(room.room_id))
  203. if client.olm.should_share_group_session(room.room_id):
  204. try:
  205. event = client.sharing_session[room.room_id]
  206. await event.wait()
  207. except KeyError:
  208. await client.share_group_session(
  209. room.room_id,
  210. ignore_unverified_devices=True,
  211. )
  212. if msgtype != "m.reaction":
  213. response = client.encrypt(room.room_id, "m.room.message", msgcontent)
  214. msgtype, content = response
  215. except Exception as e:
  216. logging(
  217. f"Error encrypting message: {e} - sending unencrypted", "error")
  218. raise
  219. if not content:
  220. msgtype = "m.room.message"
  221. content = msgcontent
  222. method, path, data = Api.room_send(
  223. client.access_token, room.room_id, msgtype, content, uuid.uuid4()
  224. )
  225. return await client._send(RoomSendResponse, method, path, data, (room.room_id,))
  226. async def accept_pending_invites(client: Optional[AsyncClient] = None):
  227. client = client or CONTEXT["client"]
  228. logging("Accepting pending invites...")
  229. for room_id in list(client.invited_rooms.keys()):
  230. logging(f"Joining room {room_id}...")
  231. response = await client.join(room_id)
  232. if isinstance(response, JoinResponse):
  233. logging(response, "debug")
  234. rooms = await client.joined_rooms()
  235. await send_message(rooms[room_id], "Hello! I'm a helpful assistant. How can I help you today?", client)
  236. else:
  237. logging(f"Error joining room {room_id}: {response}", "error")
  238. async def sync_cb(response, write_global: bool = True):
  239. logging(
  240. f"Sync response received (next batch: {response.next_batch})", "debug")
  241. SYNC_TOKEN = response.next_batch
  242. if write_global:
  243. global CONTEXT
  244. CONTEXT["sync_token"] = SYNC_TOKEN
  245. async def test_callback(room: MatrixRoom, event: Event, **kwargs):
  246. logging(
  247. f"Received event {event.__class__.__name__} in room {room.room_id}", "debug")
  248. async def init(config: ConfigParser):
  249. # Set up Matrix client
  250. try:
  251. assert "Matrix" in config
  252. assert "Homeserver" in config["Matrix"]
  253. assert "AccessToken" in config["Matrix"]
  254. except:
  255. logging("Matrix config not found or incomplete", "critical")
  256. exit(1)
  257. homeserver = config["Matrix"]["Homeserver"]
  258. access_token = config["Matrix"]["AccessToken"]
  259. device_id, user_id = await get_device_id(access_token, homeserver)
  260. device_id = config["Matrix"].get("DeviceID", device_id)
  261. user_id = config["Matrix"].get("UserID", user_id)
  262. # Set up database
  263. if "Database" in config and config["Database"].get("Path"):
  264. database = CONTEXT["database"] = initialize_database(
  265. config["Database"]["Path"])
  266. matrix_store = DuckDBStore
  267. client_config = AsyncClientConfig(
  268. store_sync_tokens=True, encryption_enabled=True, store=matrix_store)
  269. else:
  270. client_config = AsyncClientConfig(
  271. store_sync_tokens=True, encryption_enabled=False)
  272. client = AsyncClient(
  273. config["Matrix"]["Homeserver"], config=client_config)
  274. if client.config.encryption_enabled:
  275. client.store = client.config.store(
  276. user_id,
  277. device_id,
  278. database
  279. )
  280. assert client.store
  281. client.olm = Olm(client.user_id, client.device_id, client.store)
  282. client.encrypted_rooms = client.store.load_encrypted_rooms()
  283. CONTEXT["client"] = client
  284. CONTEXT["client"].access_token = config["Matrix"]["AccessToken"]
  285. CONTEXT["client"].user_id = user_id
  286. CONTEXT["client"].device_id = device_id
  287. # Set up GPT API
  288. try:
  289. assert "OpenAI" in config
  290. assert "APIKey" in config["OpenAI"]
  291. except:
  292. logging("OpenAI config not found or incomplete", "critical")
  293. exit(1)
  294. openai.api_key = config["OpenAI"]["APIKey"]
  295. if "Model" in config["OpenAI"]:
  296. CONTEXT["model"] = config["OpenAI"]["Model"]
  297. if "MaxTokens" in config["OpenAI"]:
  298. CONTEXT["max_tokens"] = int(config["OpenAI"]["MaxTokens"])
  299. if "MaxMessages" in config["OpenAI"]:
  300. CONTEXT["max_messages"] = int(config["OpenAI"]["MaxMessages"])
  301. # Listen for SIGTERM
  302. def sigterm_handler(_signo, _stack_frame):
  303. logging("Received SIGTERM - exiting...")
  304. exit()
  305. signal.signal(signal.SIGTERM, sigterm_handler)
  306. async def main(config: Optional[ConfigParser] = None, client: Optional[AsyncClient] = None):
  307. if not client and not CONTEXT.get("client"):
  308. await init(config)
  309. client = client or CONTEXT["client"]
  310. try:
  311. assert client.user_id
  312. except AssertionError:
  313. logging(
  314. "Failed to get user ID - check your access token or try setting it manually", "critical")
  315. await client.close()
  316. return
  317. logging("Starting bot...")
  318. client.add_response_callback(sync_cb, SyncResponse)
  319. logging("Syncing...")
  320. await client.sync(timeout=30000)
  321. client.add_event_callback(message_callback, RoomMessageText)
  322. client.add_event_callback(message_callback, MegolmEvent)
  323. client.add_event_callback(room_invite_callback, InviteEvent)
  324. client.add_event_callback(test_callback, Event)
  325. await accept_pending_invites() # Accept pending invites
  326. logging("Bot started")
  327. try:
  328. # Continue syncing events
  329. await client.sync_forever(timeout=30000)
  330. finally:
  331. logging("Syncing one last time...")
  332. await client.sync(timeout=30000)
  333. await client.close() # Properly close the aiohttp client session
  334. logging("Bot stopped")
  335. def initialize_database(path: os.PathLike):
  336. logging("Initializing database...")
  337. database = duckdb.connect(path)
  338. with database.cursor() as cursor:
  339. # Get the latest migration ID if the migrations table exists
  340. try:
  341. cursor.execute(
  342. """
  343. SELECT MAX(id) FROM migrations
  344. """
  345. )
  346. latest_migration = int(cursor.fetchone()[0])
  347. except:
  348. latest_migration = 0
  349. # Version 1
  350. if latest_migration < 1:
  351. cursor.execute(
  352. """
  353. CREATE TABLE IF NOT EXISTS token_usage (
  354. message_id TEXT PRIMARY KEY,
  355. room_id TEXT NOT NULL,
  356. tokens INTEGER NOT NULL,
  357. timestamp TIMESTAMP NOT NULL
  358. )
  359. """
  360. )
  361. cursor.execute(
  362. """
  363. CREATE TABLE IF NOT EXISTS migrations (
  364. id INTEGER NOT NULL,
  365. timestamp TIMESTAMP NOT NULL
  366. )
  367. """
  368. )
  369. cursor.execute(
  370. "INSERT INTO migrations (id, timestamp) VALUES (1, ?)",
  371. (datetime.now(),)
  372. )
  373. database.commit()
  374. return database
  375. async def get_device_id(access_token, homeserver):
  376. client = AsyncClient(homeserver)
  377. client.access_token = access_token
  378. logging(f"Obtaining device ID for access token {access_token}...", "debug")
  379. response = await client.whoami()
  380. if isinstance(response, WhoamiResponse):
  381. logging(
  382. f"Authenticated as {response.user_id}.")
  383. user_id = response.user_id
  384. devices = await client.devices()
  385. device_id = devices.devices[0].id
  386. await client.close()
  387. return device_id, user_id
  388. else:
  389. logging(f"Failed to obtain device ID: {response}", "error")
  390. await client.close()
  391. return None, None
  392. if __name__ == "__main__":
  393. # Parse command line arguments
  394. parser = ArgumentParser()
  395. parser.add_argument(
  396. "--config", help="Path to config file (default: config.ini in working directory)", default="config.ini")
  397. args = parser.parse_args()
  398. # Read config file
  399. config = ConfigParser()
  400. config.read(args.config)
  401. # Start bot loop
  402. try:
  403. asyncio.run(main(config))
  404. except KeyboardInterrupt:
  405. logging("Received KeyboardInterrupt - exiting...")
  406. except SystemExit:
  407. logging("Received SIGTERM - exiting...")
  408. finally:
  409. if CONTEXT["database"]:
  410. CONTEXT["database"].close()