main.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # TODO: move socket to webui app
  2. import asyncio
  3. import socketio
  4. import logging
  5. import sys
  6. import time
  7. from open_webui.models.users import Users
  8. from open_webui.env import (
  9. ENABLE_WEBSOCKET_SUPPORT,
  10. WEBSOCKET_MANAGER,
  11. WEBSOCKET_REDIS_URL,
  12. )
  13. from open_webui.utils.auth import decode_token
  14. from open_webui.socket.utils import RedisDict
  15. from open_webui.env import (
  16. GLOBAL_LOG_LEVEL,
  17. SRC_LOG_LEVELS,
  18. )
  19. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  20. log = logging.getLogger(__name__)
  21. log.setLevel(SRC_LOG_LEVELS["SOCKET"])
  22. if WEBSOCKET_MANAGER == "redis":
  23. mgr = socketio.AsyncRedisManager(WEBSOCKET_REDIS_URL)
  24. sio = socketio.AsyncServer(
  25. cors_allowed_origins=[],
  26. async_mode="asgi",
  27. transports=(
  28. ["polling", "websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]
  29. ),
  30. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  31. always_connect=True,
  32. client_manager=mgr,
  33. )
  34. else:
  35. sio = socketio.AsyncServer(
  36. cors_allowed_origins=[],
  37. async_mode="asgi",
  38. transports=(
  39. ["polling", "websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]
  40. ),
  41. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  42. always_connect=True,
  43. )
  44. # Dictionary to maintain the user pool
  45. if WEBSOCKET_MANAGER == "redis":
  46. SESSION_POOL = RedisDict("open-webui:session_pool", redis_url=WEBSOCKET_REDIS_URL)
  47. USER_POOL = RedisDict("open-webui:user_pool", redis_url=WEBSOCKET_REDIS_URL)
  48. USAGE_POOL = RedisDict("open-webui:usage_pool", redis_url=WEBSOCKET_REDIS_URL)
  49. else:
  50. SESSION_POOL = {}
  51. USER_POOL = {}
  52. USAGE_POOL = {}
  53. # Timeout duration in seconds
  54. TIMEOUT_DURATION = 3
  55. async def periodic_usage_pool_cleanup():
  56. while True:
  57. now = int(time.time())
  58. for model_id, connections in list(USAGE_POOL.items()):
  59. # Creating a list of sids to remove if they have timed out
  60. expired_sids = [
  61. sid
  62. for sid, details in connections.items()
  63. if now - details["updated_at"] > TIMEOUT_DURATION
  64. ]
  65. for sid in expired_sids:
  66. del connections[sid]
  67. if not connections:
  68. log.debug(f"Cleaning up model {model_id} from usage pool")
  69. del USAGE_POOL[model_id]
  70. else:
  71. USAGE_POOL[model_id] = connections
  72. # Emit updated usage information after cleaning
  73. await sio.emit("usage", {"models": get_models_in_use()})
  74. await asyncio.sleep(TIMEOUT_DURATION)
  75. app = socketio.ASGIApp(
  76. sio,
  77. socketio_path="/ws/socket.io",
  78. )
  79. def get_models_in_use():
  80. # List models that are currently in use
  81. models_in_use = list(USAGE_POOL.keys())
  82. return models_in_use
  83. @sio.on("usage")
  84. async def usage(sid, data):
  85. model_id = data["model"]
  86. # Record the timestamp for the last update
  87. current_time = int(time.time())
  88. # Store the new usage data and task
  89. USAGE_POOL[model_id] = {
  90. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  91. sid: {"updated_at": current_time},
  92. }
  93. # Broadcast the usage data to all clients
  94. await sio.emit("usage", {"models": get_models_in_use()})
  95. @sio.event
  96. async def connect(sid, environ, auth):
  97. user = None
  98. if auth and "token" in auth:
  99. data = decode_token(auth["token"])
  100. if data is not None and "id" in data:
  101. user = Users.get_user_by_id(data["id"])
  102. if user:
  103. SESSION_POOL[sid] = user.id
  104. if user.id in USER_POOL:
  105. USER_POOL[user.id].append(sid)
  106. else:
  107. USER_POOL[user.id] = [sid]
  108. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  109. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  110. await sio.emit("usage", {"models": get_models_in_use()})
  111. @sio.on("user-join")
  112. async def user_join(sid, data):
  113. # print("user-join", sid, data)
  114. auth = data["auth"] if "auth" in data else None
  115. if not auth or "token" not in auth:
  116. return
  117. data = decode_token(auth["token"])
  118. if data is None or "id" not in data:
  119. return
  120. user = Users.get_user_by_id(data["id"])
  121. if not user:
  122. return
  123. SESSION_POOL[sid] = user.id
  124. if user.id in USER_POOL:
  125. USER_POOL[user.id].append(sid)
  126. else:
  127. USER_POOL[user.id] = [sid]
  128. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  129. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  130. @sio.on("user-count")
  131. async def user_count(sid):
  132. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  133. @sio.on("chat")
  134. async def chat(sid, data):
  135. print("chat", sid, SESSION_POOL[sid], data)
  136. @sio.event
  137. async def disconnect(sid):
  138. if sid in SESSION_POOL:
  139. user_id = SESSION_POOL[sid]
  140. del SESSION_POOL[sid]
  141. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  142. if len(USER_POOL[user_id]) == 0:
  143. del USER_POOL[user_id]
  144. await sio.emit("user-count", {"count": len(USER_POOL)})
  145. else:
  146. pass
  147. # print(f"Unknown session ID {sid} disconnected")
  148. def get_event_emitter(request_info):
  149. async def __event_emitter__(event_data):
  150. await sio.emit(
  151. "chat-events",
  152. {
  153. "chat_id": request_info["chat_id"],
  154. "message_id": request_info["message_id"],
  155. "data": event_data,
  156. },
  157. to=request_info["session_id"],
  158. )
  159. return __event_emitter__
  160. def get_event_call(request_info):
  161. async def __event_call__(event_data):
  162. response = await sio.call(
  163. "chat-events",
  164. {
  165. "chat_id": request_info["chat_id"],
  166. "message_id": request_info["message_id"],
  167. "data": event_data,
  168. },
  169. to=request_info["session_id"],
  170. )
  171. return response
  172. return __event_call__