main.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. import asyncio
  2. import socketio
  3. from open_webui.apps.webui.models.users import Users
  4. from open_webui.env import (
  5. ENABLE_WEBSOCKET_SUPPORT,
  6. WEBSOCKET_MANAGER,
  7. WEBSOCKET_REDIS_URL,
  8. )
  9. from open_webui.utils.utils import decode_token
  10. if WEBSOCKET_MANAGER == "redis":
  11. mgr = socketio.AsyncRedisManager(WEBSOCKET_REDIS_URL)
  12. sio = socketio.AsyncServer(
  13. cors_allowed_origins=[],
  14. async_mode="asgi",
  15. transports=(
  16. ["polling", "websocket"] if ENABLE_WEBSOCKET_SUPPORT else ["polling"]
  17. ),
  18. allow_upgrades=ENABLE_WEBSOCKET_SUPPORT,
  19. always_connect=True,
  20. client_manager=mgr,
  21. )
  22. else:
  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. )
  32. app = socketio.ASGIApp(sio, socketio_path="/ws/socket.io")
  33. # Dictionary to maintain the user pool
  34. SESSION_POOL = {}
  35. USER_POOL = {}
  36. USAGE_POOL = {}
  37. # Timeout duration in seconds
  38. TIMEOUT_DURATION = 3
  39. @sio.event
  40. async def connect(sid, environ, auth):
  41. user = None
  42. if auth and "token" in auth:
  43. data = decode_token(auth["token"])
  44. if data is not None and "id" in data:
  45. user = Users.get_user_by_id(data["id"])
  46. if user:
  47. SESSION_POOL[sid] = user.id
  48. if user.id in USER_POOL:
  49. USER_POOL[user.id].append(sid)
  50. else:
  51. USER_POOL[user.id] = [sid]
  52. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  53. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  54. await sio.emit("usage", {"models": get_models_in_use()})
  55. @sio.on("user-join")
  56. async def user_join(sid, data):
  57. # print("user-join", sid, data)
  58. auth = data["auth"] if "auth" in data else None
  59. if not auth or "token" not in auth:
  60. return
  61. data = decode_token(auth["token"])
  62. if data is None or "id" not in data:
  63. return
  64. user = Users.get_user_by_id(data["id"])
  65. if not user:
  66. return
  67. SESSION_POOL[sid] = user.id
  68. if user.id in USER_POOL:
  69. USER_POOL[user.id].append(sid)
  70. else:
  71. USER_POOL[user.id] = [sid]
  72. # print(f"user {user.name}({user.id}) connected with session ID {sid}")
  73. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  74. @sio.on("user-count")
  75. async def user_count(sid):
  76. await sio.emit("user-count", {"count": len(set(USER_POOL))})
  77. def get_models_in_use():
  78. # Aggregate all models in use
  79. models_in_use = []
  80. for model_id, data in USAGE_POOL.items():
  81. models_in_use.append(model_id)
  82. return models_in_use
  83. @sio.on("usage")
  84. async def usage(sid, data):
  85. model_id = data["model"]
  86. # Cancel previous callback if there is one
  87. if model_id in USAGE_POOL:
  88. USAGE_POOL[model_id]["callback"].cancel()
  89. # Store the new usage data and task
  90. if model_id in USAGE_POOL:
  91. USAGE_POOL[model_id]["sids"].append(sid)
  92. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  93. else:
  94. USAGE_POOL[model_id] = {"sids": [sid]}
  95. # Schedule a task to remove the usage data after TIMEOUT_DURATION
  96. USAGE_POOL[model_id]["callback"] = asyncio.create_task(
  97. remove_after_timeout(sid, model_id)
  98. )
  99. # Broadcast the usage data to all clients
  100. await sio.emit("usage", {"models": get_models_in_use()})
  101. async def remove_after_timeout(sid, model_id):
  102. try:
  103. await asyncio.sleep(TIMEOUT_DURATION)
  104. if model_id in USAGE_POOL:
  105. # print(USAGE_POOL[model_id]["sids"])
  106. USAGE_POOL[model_id]["sids"].remove(sid)
  107. USAGE_POOL[model_id]["sids"] = list(set(USAGE_POOL[model_id]["sids"]))
  108. if len(USAGE_POOL[model_id]["sids"]) == 0:
  109. del USAGE_POOL[model_id]
  110. # Broadcast the usage data to all clients
  111. await sio.emit("usage", {"models": get_models_in_use()})
  112. except asyncio.CancelledError:
  113. # Task was cancelled due to new 'usage' event
  114. pass
  115. @sio.event
  116. async def disconnect(sid):
  117. if sid in SESSION_POOL:
  118. user_id = SESSION_POOL[sid]
  119. del SESSION_POOL[sid]
  120. USER_POOL[user_id].remove(sid)
  121. if len(USER_POOL[user_id]) == 0:
  122. del USER_POOL[user_id]
  123. await sio.emit("user-count", {"count": len(USER_POOL)})
  124. else:
  125. pass
  126. # print(f"Unknown session ID {sid} disconnected")
  127. def get_event_emitter(request_info):
  128. async def __event_emitter__(event_data):
  129. await sio.emit(
  130. "chat-events",
  131. {
  132. "chat_id": request_info["chat_id"],
  133. "message_id": request_info["message_id"],
  134. "data": event_data,
  135. },
  136. to=request_info["session_id"],
  137. )
  138. return __event_emitter__
  139. def get_event_call(request_info):
  140. async def __event_call__(event_data):
  141. response = await sio.call(
  142. "chat-events",
  143. {
  144. "chat_id": request_info["chat_id"],
  145. "message_id": request_info["message_id"],
  146. "data": event_data,
  147. },
  148. to=request_info["session_id"],
  149. )
  150. return response
  151. return __event_call__