main.py 10 KB

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