models.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. from typing import Optional
  2. import io
  3. import base64
  4. import json
  5. import asyncio
  6. import logging
  7. from open_webui.models.models import (
  8. ModelForm,
  9. ModelModel,
  10. ModelResponse,
  11. ModelUserResponse,
  12. Models,
  13. )
  14. from pydantic import BaseModel
  15. from open_webui.constants import ERROR_MESSAGES
  16. from fastapi import (
  17. APIRouter,
  18. Depends,
  19. HTTPException,
  20. Request,
  21. status,
  22. Response,
  23. )
  24. from fastapi.responses import FileResponse, StreamingResponse
  25. from open_webui.utils.auth import get_admin_user, get_verified_user
  26. from open_webui.utils.access_control import has_access, has_permission
  27. from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL, STATIC_DIR
  28. log = logging.getLogger(__name__)
  29. router = APIRouter()
  30. def validate_model_id(model_id: str) -> bool:
  31. return model_id and len(model_id) <= 256
  32. ###########################
  33. # GetModels
  34. ###########################
  35. @router.get("/", response_model=list[ModelUserResponse])
  36. async def get_models(id: Optional[str] = None, user=Depends(get_verified_user)):
  37. if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
  38. return Models.get_models()
  39. else:
  40. return Models.get_models_by_user_id(user.id)
  41. ###########################
  42. # GetBaseModels
  43. ###########################
  44. @router.get("/base", response_model=list[ModelResponse])
  45. async def get_base_models(user=Depends(get_admin_user)):
  46. return Models.get_base_models()
  47. ############################
  48. # CreateNewModel
  49. ############################
  50. @router.post("/create", response_model=Optional[ModelModel])
  51. async def create_new_model(
  52. request: Request,
  53. form_data: ModelForm,
  54. user=Depends(get_verified_user),
  55. ):
  56. if user.role != "admin" and not has_permission(
  57. user.id, "workspace.models", request.app.state.config.USER_PERMISSIONS
  58. ):
  59. raise HTTPException(
  60. status_code=status.HTTP_401_UNAUTHORIZED,
  61. detail=ERROR_MESSAGES.UNAUTHORIZED,
  62. )
  63. model = Models.get_model_by_id(form_data.id)
  64. if model:
  65. raise HTTPException(
  66. status_code=status.HTTP_401_UNAUTHORIZED,
  67. detail=ERROR_MESSAGES.MODEL_ID_TAKEN,
  68. )
  69. if not validate_model_id(form_data.id):
  70. raise HTTPException(
  71. status_code=status.HTTP_400_BAD_REQUEST,
  72. detail=ERROR_MESSAGES.MODEL_ID_TOO_LONG,
  73. )
  74. else:
  75. model = Models.insert_new_model(form_data, user.id)
  76. if model:
  77. return model
  78. else:
  79. raise HTTPException(
  80. status_code=status.HTTP_401_UNAUTHORIZED,
  81. detail=ERROR_MESSAGES.DEFAULT(),
  82. )
  83. ############################
  84. # ExportModels
  85. ############################
  86. @router.get("/export", response_model=list[ModelModel])
  87. async def export_models(user=Depends(get_admin_user)):
  88. return Models.get_models()
  89. ############################
  90. # ImportModels
  91. ############################
  92. class ModelsImportForm(BaseModel):
  93. models: list[dict]
  94. @router.post("/import", response_model=bool)
  95. async def import_models(
  96. user: str = Depends(get_admin_user), form_data: ModelsImportForm = (...)
  97. ):
  98. try:
  99. data = form_data.models
  100. if isinstance(data, list):
  101. for model_data in data:
  102. # Here, you can add logic to validate model_data if needed
  103. model_id = model_data.get("id")
  104. if model_id and validate_model_id(model_id):
  105. existing_model = Models.get_model_by_id(model_id)
  106. if existing_model:
  107. # Update existing model
  108. model_data["meta"] = model_data.get("meta", {})
  109. model_data["params"] = model_data.get("params", {})
  110. updated_model = ModelForm(
  111. **{**existing_model.model_dump(), **model_data}
  112. )
  113. Models.update_model_by_id(model_id, updated_model)
  114. else:
  115. # Insert new model
  116. model_data["meta"] = model_data.get("meta", {})
  117. model_data["params"] = model_data.get("params", {})
  118. new_model = ModelForm(**model_data)
  119. Models.insert_new_model(user_id=user.id, form_data=new_model)
  120. return True
  121. else:
  122. raise HTTPException(status_code=400, detail="Invalid JSON format")
  123. except Exception as e:
  124. log.exception(e)
  125. raise HTTPException(status_code=500, detail=str(e))
  126. ############################
  127. # SyncModels
  128. ############################
  129. class SyncModelsForm(BaseModel):
  130. models: list[ModelModel] = []
  131. @router.post("/sync", response_model=list[ModelModel])
  132. async def sync_models(
  133. request: Request, form_data: SyncModelsForm, user=Depends(get_admin_user)
  134. ):
  135. return Models.sync_models(user.id, form_data.models)
  136. ###########################
  137. # GetModelById
  138. ###########################
  139. # Note: We're not using the typical url path param here, but instead using a query parameter to allow '/' in the id
  140. @router.get("/model", response_model=Optional[ModelResponse])
  141. async def get_model_by_id(id: str, user=Depends(get_verified_user)):
  142. model = Models.get_model_by_id(id)
  143. if model:
  144. if (
  145. (user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL)
  146. or model.user_id == user.id
  147. or has_access(user.id, "read", model.access_control)
  148. ):
  149. return model
  150. else:
  151. raise HTTPException(
  152. status_code=status.HTTP_401_UNAUTHORIZED,
  153. detail=ERROR_MESSAGES.NOT_FOUND,
  154. )
  155. ###########################
  156. # GetModelById
  157. ###########################
  158. @router.get("/model/profile/image")
  159. async def get_model_profile_image(id: str, user=Depends(get_verified_user)):
  160. model = Models.get_model_by_id(id)
  161. if model:
  162. if model.meta.profile_image_url:
  163. if model.meta.profile_image_url.startswith("http"):
  164. return Response(
  165. status_code=status.HTTP_302_FOUND,
  166. headers={"Location": model.meta.profile_image_url},
  167. )
  168. elif model.meta.profile_image_url.startswith("data:image"):
  169. try:
  170. header, base64_data = model.meta.profile_image_url.split(",", 1)
  171. image_data = base64.b64decode(base64_data)
  172. image_buffer = io.BytesIO(image_data)
  173. return StreamingResponse(
  174. image_buffer,
  175. media_type="image/png",
  176. headers={"Content-Disposition": "inline; filename=image.png"},
  177. )
  178. except Exception as e:
  179. pass
  180. return FileResponse(f"{STATIC_DIR}/favicon.png")
  181. else:
  182. return FileResponse(f"{STATIC_DIR}/favicon.png")
  183. ############################
  184. # ToggleModelById
  185. ############################
  186. @router.post("/model/toggle", response_model=Optional[ModelResponse])
  187. async def toggle_model_by_id(id: str, user=Depends(get_verified_user)):
  188. model = Models.get_model_by_id(id)
  189. if model:
  190. if (
  191. user.role == "admin"
  192. or model.user_id == user.id
  193. or has_access(user.id, "write", model.access_control)
  194. ):
  195. model = Models.toggle_model_by_id(id)
  196. if model:
  197. return model
  198. else:
  199. raise HTTPException(
  200. status_code=status.HTTP_400_BAD_REQUEST,
  201. detail=ERROR_MESSAGES.DEFAULT("Error updating function"),
  202. )
  203. else:
  204. raise HTTPException(
  205. status_code=status.HTTP_401_UNAUTHORIZED,
  206. detail=ERROR_MESSAGES.UNAUTHORIZED,
  207. )
  208. else:
  209. raise HTTPException(
  210. status_code=status.HTTP_401_UNAUTHORIZED,
  211. detail=ERROR_MESSAGES.NOT_FOUND,
  212. )
  213. ############################
  214. # UpdateModelById
  215. ############################
  216. @router.post("/model/update", response_model=Optional[ModelModel])
  217. async def update_model_by_id(
  218. id: str,
  219. form_data: ModelForm,
  220. user=Depends(get_verified_user),
  221. ):
  222. model = Models.get_model_by_id(id)
  223. if not model:
  224. raise HTTPException(
  225. status_code=status.HTTP_401_UNAUTHORIZED,
  226. detail=ERROR_MESSAGES.NOT_FOUND,
  227. )
  228. if (
  229. model.user_id != user.id
  230. and not has_access(user.id, "write", model.access_control)
  231. and user.role != "admin"
  232. ):
  233. raise HTTPException(
  234. status_code=status.HTTP_400_BAD_REQUEST,
  235. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  236. )
  237. model = Models.update_model_by_id(id, form_data)
  238. return model
  239. ############################
  240. # DeleteModelById
  241. ############################
  242. @router.delete("/model/delete", response_model=bool)
  243. async def delete_model_by_id(id: str, user=Depends(get_verified_user)):
  244. model = Models.get_model_by_id(id)
  245. if not model:
  246. raise HTTPException(
  247. status_code=status.HTTP_401_UNAUTHORIZED,
  248. detail=ERROR_MESSAGES.NOT_FOUND,
  249. )
  250. if (
  251. user.role != "admin"
  252. and model.user_id != user.id
  253. and not has_access(user.id, "write", model.access_control)
  254. ):
  255. raise HTTPException(
  256. status_code=status.HTTP_401_UNAUTHORIZED,
  257. detail=ERROR_MESSAGES.UNAUTHORIZED,
  258. )
  259. result = Models.delete_model_by_id(id)
  260. return result
  261. @router.delete("/delete/all", response_model=bool)
  262. async def delete_all_models(user=Depends(get_admin_user)):
  263. result = Models.delete_all_models()
  264. return result