main.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. async def on_startup():
  75. asyncio.create_task(periodic_usage_pool_cleanup())
  76. app = socketio.ASGIApp(
  77. sio,
  78. socketio_path="/ws/socket.io",
  79. on_startup=on_startup(),
  80. )
  81. def get_models_in_use():
  82. # List models that are currently in use
  83. models_in_use = list(USAGE_POOL.keys())
  84. return models_in_use
  85. @sio.on("usage")
  86. async def usage(sid, data):
  87. model_id = data["model"]
  88. # Record the timestamp for the last update
  89. current_time = int(time.time())
  90. # Store the new usage data and task
  91. USAGE_POOL[model_id] = {
  92. **(USAGE_POOL[model_id] if model_id in USAGE_POOL else {}),
  93. sid: {"updated_at": current_time},
  94. }
  95. # Broadcast the usage data to all clients
  96. await sio.emit("usage", {"models": get_models_in_use()})
  97. @sio.event
  98. async def connect(sid, environ, auth):
  99. user = None
  100. if auth and "token" in auth:
  101. data = decode_token(auth["token"])
  102. if data is not None and "id" in data:
  103. user = Users.get_user_by_id(data["id"])
  104. if user:
  105. SESSION_POOL[sid] = user.id
  106. if user.id in USER_POOL:
  107. USER_POOL[user.id].append(sid)
  108. else:
  109. USER_POOL[user.id] = [sid]
  110. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  111. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  112. await sio.emit("usage", {"models": get_models_in_use()})
  113. @sio.on("user-join")
  114. async def user_join(sid, data):
  115. # print("user-join", sid, data)
  116. auth = data["auth"] if "auth" in data else None
  117. if not auth or "token" not in auth:
  118. return
  119. data = decode_token(auth["token"])
  120. if data is None or "id" not in data:
  121. return
  122. user = Users.get_user_by_id(data["id"])
  123. if not user:
  124. return
  125. SESSION_POOL[sid] = user.id
  126. if user.id in USER_POOL:
  127. USER_POOL[user.id].append(sid)
  128. else:
  129. USER_POOL[user.id] = [sid]
  130. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  131. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  132. @sio.on("user-count")
  133. async def user_count(sid):
  134. await sio.emit("user-count", {"count": len(USER_POOL.items())})
  135. @sio.event
  136. async def disconnect(sid):
  137. if sid in SESSION_POOL:
  138. user_id = SESSION_POOL[sid]
  139. del SESSION_POOL[sid]
  140. USER_POOL[user_id] = [_sid for _sid in USER_POOL[user_id] if _sid != sid]
  141. if len(USER_POOL[user_id]) == 0:
  142. del USER_POOL[user_id]
  143. await sio.emit("user-count", {"count": len(USER_POOL)})
  144. else:
  145. pass
  146. # print(f"Unknown session ID {sid} disconnected")
  147. def get_event_emitter(request_info):
  148. async def __event_emitter__(event_data):
  149. await sio.emit(
  150. "chat-events",
  151. {
  152. "chat_id": request_info["chat_id"],
  153. "message_id": request_info["message_id"],
  154. "data": event_data,
  155. },
  156. to=request_info["session_id"],
  157. )
  158. return __event_emitter__
  159. def get_event_call(request_info):
  160. async def __event_call__(event_data):
  161. response = await sio.call(
  162. "chat-events",
  163. {
  164. "chat_id": request_info["chat_id"],
  165. "message_id": request_info["message_id"],
  166. "data": event_data,
  167. },
  168. to=request_info["session_id"],
  169. )
  170. return response
  171. return __event_call__