main.py 11 KB

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