main.py 11 KB

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