main.py 5.6 KB

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