main.py 9.3 KB

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