main.py 11 KB

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