main.py 9.4 KB

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