main.py 10 KB

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