main.py 9.2 KB

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