main.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. from fastapi import FastAPI, Depends, HTTPException
  2. from fastapi.routing import APIRoute
  3. from fastapi.middleware.cors import CORSMiddleware
  4. import logging
  5. from fastapi import FastAPI, Request, Depends, status, Response
  6. from fastapi.responses import JSONResponse
  7. from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
  8. from starlette.responses import StreamingResponse
  9. import json
  10. import requests
  11. from pydantic import BaseModel
  12. from typing import Optional, List
  13. from utils.utils import get_verified_user, get_current_user, get_admin_user
  14. from config import SRC_LOG_LEVELS, ENV
  15. from constants import ERROR_MESSAGES
  16. log = logging.getLogger(__name__)
  17. log.setLevel(SRC_LOG_LEVELS["LITELLM"])
  18. from config import MODEL_FILTER_ENABLED, MODEL_FILTER_LIST, DATA_DIR
  19. import asyncio
  20. import subprocess
  21. import yaml
  22. app = FastAPI()
  23. origins = ["*"]
  24. app.add_middleware(
  25. CORSMiddleware,
  26. allow_origins=origins,
  27. allow_credentials=True,
  28. allow_methods=["*"],
  29. allow_headers=["*"],
  30. )
  31. LITELLM_CONFIG_DIR = f"{DATA_DIR}/litellm/config.yaml"
  32. with open(LITELLM_CONFIG_DIR, "r") as file:
  33. litellm_config = yaml.safe_load(file)
  34. app.state.CONFIG = litellm_config
  35. # Global variable to store the subprocess reference
  36. background_process = None
  37. async def run_background_process(command):
  38. global background_process
  39. log.info("run_background_process")
  40. try:
  41. # Log the command to be executed
  42. log.info(f"Executing command: {command}")
  43. # Execute the command and create a subprocess
  44. process = await asyncio.create_subprocess_exec(
  45. *command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE
  46. )
  47. background_process = process
  48. log.info("Subprocess started successfully.")
  49. # Capture STDERR for debugging purposes
  50. stderr_output = await process.stderr.read()
  51. stderr_text = stderr_output.decode().strip()
  52. if stderr_text:
  53. log.info(f"Subprocess STDERR: {stderr_text}")
  54. # log.info output line by line
  55. async for line in process.stdout:
  56. log.info(line.decode().strip())
  57. # Wait for the process to finish
  58. returncode = await process.wait()
  59. log.info(f"Subprocess exited with return code {returncode}")
  60. except Exception as e:
  61. log.error(f"Failed to start subprocess: {e}")
  62. raise # Optionally re-raise the exception if you want it to propagate
  63. async def start_litellm_background():
  64. log.info("start_litellm_background")
  65. # Command to run in the background
  66. command = (
  67. "litellm --port 14365 --telemetry False --config ./data/litellm/config.yaml"
  68. )
  69. await run_background_process(command)
  70. async def shutdown_litellm_background():
  71. log.info("shutdown_litellm_background")
  72. global background_process
  73. if background_process:
  74. background_process.terminate()
  75. await background_process.wait() # Ensure the process has terminated
  76. log.info("Subprocess terminated")
  77. background_process = None
  78. @app.on_event("startup")
  79. async def startup_event():
  80. log.info("startup_event")
  81. # TODO: Check config.yaml file and create one
  82. asyncio.create_task(start_litellm_background())
  83. app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
  84. app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  85. @app.get("/")
  86. async def get_status():
  87. return {"status": True}
  88. async def restart_litellm():
  89. """
  90. Endpoint to restart the litellm background service.
  91. """
  92. log.info("Requested restart of litellm service.")
  93. try:
  94. # Shut down the existing process if it is running
  95. await shutdown_litellm_background()
  96. log.info("litellm service shutdown complete.")
  97. # Restart the background service
  98. asyncio.create_task(start_litellm_background())
  99. log.info("litellm service restart complete.")
  100. return {
  101. "status": "success",
  102. "message": "litellm service restarted successfully.",
  103. }
  104. except Exception as e:
  105. log.info(f"Error restarting litellm service: {e}")
  106. raise HTTPException(
  107. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
  108. )
  109. @app.get("/restart")
  110. async def restart_litellm_handler(user=Depends(get_admin_user)):
  111. return await restart_litellm()
  112. @app.get("/config")
  113. async def get_config(user=Depends(get_admin_user)):
  114. return app.state.CONFIG
  115. class LiteLLMConfigForm(BaseModel):
  116. general_settings: Optional[dict] = None
  117. litellm_settings: Optional[dict] = None
  118. model_list: Optional[List[dict]] = None
  119. router_settings: Optional[dict] = None
  120. @app.post("/config/update")
  121. async def update_config(form_data: LiteLLMConfigForm, user=Depends(get_admin_user)):
  122. app.state.CONFIG = form_data.model_dump(exclude_none=True)
  123. with open(LITELLM_CONFIG_DIR, "w") as file:
  124. yaml.dump(app.state.CONFIG, file)
  125. await restart_litellm()
  126. return app.state.CONFIG
  127. @app.get("/models")
  128. @app.get("/v1/models")
  129. async def get_models(user=Depends(get_current_user)):
  130. while not background_process:
  131. await asyncio.sleep(0.1)
  132. url = "http://localhost:14365/v1"
  133. r = None
  134. try:
  135. r = requests.request(method="GET", url=f"{url}/models")
  136. r.raise_for_status()
  137. data = r.json()
  138. if app.state.MODEL_FILTER_ENABLED:
  139. if user and user.role == "user":
  140. data["data"] = list(
  141. filter(
  142. lambda model: model["id"] in app.state.MODEL_FILTER_LIST,
  143. data["data"],
  144. )
  145. )
  146. return data
  147. except Exception as e:
  148. log.exception(e)
  149. error_detail = "Open WebUI: Server Connection Error"
  150. if r is not None:
  151. try:
  152. res = r.json()
  153. if "error" in res:
  154. error_detail = f"External: {res['error']}"
  155. except:
  156. error_detail = f"External: {e}"
  157. raise HTTPException(
  158. status_code=r.status_code if r else 500,
  159. detail=error_detail,
  160. )
  161. @app.get("/model/info")
  162. async def get_model_list(user=Depends(get_admin_user)):
  163. return {"data": app.state.CONFIG["model_list"]}
  164. class AddLiteLLMModelForm(BaseModel):
  165. model_name: str
  166. litellm_params: dict
  167. @app.post("/model/new")
  168. async def add_model_to_config(
  169. form_data: AddLiteLLMModelForm, user=Depends(get_admin_user)
  170. ):
  171. app.state.CONFIG["model_list"].append(form_data.model_dump())
  172. with open(LITELLM_CONFIG_DIR, "w") as file:
  173. yaml.dump(app.state.CONFIG, file)
  174. await restart_litellm()
  175. return {"message": "model added"}
  176. class DeleteLiteLLMModelForm(BaseModel):
  177. id: str
  178. @app.post("/model/delete")
  179. async def delete_model_from_config(
  180. form_data: DeleteLiteLLMModelForm, user=Depends(get_admin_user)
  181. ):
  182. app.state.CONFIG["model_list"] = [
  183. model
  184. for model in app.state.CONFIG["model_list"]
  185. if model["model_name"] != form_data.id
  186. ]
  187. with open(LITELLM_CONFIG_DIR, "w") as file:
  188. yaml.dump(app.state.CONFIG, file)
  189. await restart_litellm()
  190. return {"message": "model deleted"}
  191. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  192. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  193. body = await request.body()
  194. url = "http://localhost:14365"
  195. target_url = f"{url}/{path}"
  196. headers = {}
  197. # headers["Authorization"] = f"Bearer {key}"
  198. headers["Content-Type"] = "application/json"
  199. r = None
  200. try:
  201. r = requests.request(
  202. method=request.method,
  203. url=target_url,
  204. data=body,
  205. headers=headers,
  206. stream=True,
  207. )
  208. r.raise_for_status()
  209. # Check if response is SSE
  210. if "text/event-stream" in r.headers.get("Content-Type", ""):
  211. return StreamingResponse(
  212. r.iter_content(chunk_size=8192),
  213. status_code=r.status_code,
  214. headers=dict(r.headers),
  215. )
  216. else:
  217. response_data = r.json()
  218. return response_data
  219. except Exception as e:
  220. log.exception(e)
  221. error_detail = "Open WebUI: Server Connection Error"
  222. if r is not None:
  223. try:
  224. res = r.json()
  225. if "error" in res:
  226. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  227. except:
  228. error_detail = f"External: {e}"
  229. raise HTTPException(
  230. status_code=r.status_code if r else 500, detail=error_detail
  231. )