main.py 5.0 KB

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