main.py 5.8 KB

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