main.py 4.5 KB

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