main.py 9.3 KB

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