main.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. from fastapi import FastAPI, Request, Response, HTTPException, Depends
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from fastapi.responses import StreamingResponse, JSONResponse, FileResponse
  4. import requests
  5. import aiohttp
  6. import asyncio
  7. import json
  8. import logging
  9. from pydantic import BaseModel
  10. from apps.webui.models.models import Models
  11. from apps.webui.models.users import Users
  12. from constants import ERROR_MESSAGES
  13. from utils.utils import (
  14. decode_token,
  15. get_current_user,
  16. get_verified_user,
  17. get_admin_user,
  18. )
  19. from config import (
  20. SRC_LOG_LEVELS,
  21. ENABLE_OPENAI_API,
  22. OPENAI_API_BASE_URLS,
  23. OPENAI_API_KEYS,
  24. CACHE_DIR,
  25. ENABLE_MODEL_FILTER,
  26. MODEL_FILTER_LIST,
  27. AppConfig,
  28. )
  29. from typing import List, Optional
  30. import hashlib
  31. from pathlib import Path
  32. log = logging.getLogger(__name__)
  33. log.setLevel(SRC_LOG_LEVELS["OPENAI"])
  34. app = FastAPI()
  35. app.add_middleware(
  36. CORSMiddleware,
  37. allow_origins=["*"],
  38. allow_credentials=True,
  39. allow_methods=["*"],
  40. allow_headers=["*"],
  41. )
  42. app.state.config = AppConfig()
  43. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  44. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  45. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  46. app.state.config.OPENAI_API_BASE_URLS = OPENAI_API_BASE_URLS
  47. app.state.config.OPENAI_API_KEYS = OPENAI_API_KEYS
  48. app.state.MODELS = {}
  49. @app.middleware("http")
  50. async def check_url(request: Request, call_next):
  51. if len(app.state.MODELS) == 0:
  52. await get_all_models()
  53. else:
  54. pass
  55. response = await call_next(request)
  56. return response
  57. @app.get("/config")
  58. async def get_config(user=Depends(get_admin_user)):
  59. return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
  60. class OpenAIConfigForm(BaseModel):
  61. enable_openai_api: Optional[bool] = None
  62. @app.post("/config/update")
  63. async def update_config(form_data: OpenAIConfigForm, user=Depends(get_admin_user)):
  64. app.state.config.ENABLE_OPENAI_API = form_data.enable_openai_api
  65. return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
  66. class UrlsUpdateForm(BaseModel):
  67. urls: List[str]
  68. class KeysUpdateForm(BaseModel):
  69. keys: List[str]
  70. @app.get("/urls")
  71. async def get_openai_urls(user=Depends(get_admin_user)):
  72. return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
  73. @app.post("/urls/update")
  74. async def update_openai_urls(form_data: UrlsUpdateForm, user=Depends(get_admin_user)):
  75. await get_all_models()
  76. app.state.config.OPENAI_API_BASE_URLS = form_data.urls
  77. return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
  78. @app.get("/keys")
  79. async def get_openai_keys(user=Depends(get_admin_user)):
  80. return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
  81. @app.post("/keys/update")
  82. async def update_openai_key(form_data: KeysUpdateForm, user=Depends(get_admin_user)):
  83. app.state.config.OPENAI_API_KEYS = form_data.keys
  84. return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
  85. @app.post("/audio/speech")
  86. async def speech(request: Request, user=Depends(get_verified_user)):
  87. idx = None
  88. try:
  89. idx = app.state.config.OPENAI_API_BASE_URLS.index("https://api.openai.com/v1")
  90. body = await request.body()
  91. name = hashlib.sha256(body).hexdigest()
  92. SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
  93. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  94. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  95. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  96. # Check if the file already exists in the cache
  97. if file_path.is_file():
  98. return FileResponse(file_path)
  99. headers = {}
  100. headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEYS[idx]}"
  101. headers["Content-Type"] = "application/json"
  102. if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
  103. headers["HTTP-Referer"] = "https://openwebui.com/"
  104. headers["X-Title"] = "Open WebUI"
  105. r = None
  106. try:
  107. r = requests.post(
  108. url=f"{app.state.config.OPENAI_API_BASE_URLS[idx]}/audio/speech",
  109. data=body,
  110. headers=headers,
  111. stream=True,
  112. )
  113. r.raise_for_status()
  114. # Save the streaming content to a file
  115. with open(file_path, "wb") as f:
  116. for chunk in r.iter_content(chunk_size=8192):
  117. f.write(chunk)
  118. with open(file_body_path, "w") as f:
  119. json.dump(json.loads(body.decode("utf-8")), f)
  120. # Return the saved file
  121. return FileResponse(file_path)
  122. except Exception as e:
  123. log.exception(e)
  124. error_detail = "Open WebUI: Server Connection Error"
  125. if r is not None:
  126. try:
  127. res = r.json()
  128. if "error" in res:
  129. error_detail = f"External: {res['error']}"
  130. except:
  131. error_detail = f"External: {e}"
  132. raise HTTPException(
  133. status_code=r.status_code if r else 500, detail=error_detail
  134. )
  135. except ValueError:
  136. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.OPENAI_NOT_FOUND)
  137. async def fetch_url(url, key):
  138. timeout = aiohttp.ClientTimeout(total=5)
  139. try:
  140. headers = {"Authorization": f"Bearer {key}"}
  141. async with aiohttp.ClientSession(timeout=timeout) as session:
  142. async with session.get(url, headers=headers) as response:
  143. return await response.json()
  144. except Exception as e:
  145. # Handle connection error here
  146. log.error(f"Connection error: {e}")
  147. return None
  148. def merge_models_lists(model_lists):
  149. log.debug(f"merge_models_lists {model_lists}")
  150. merged_list = []
  151. for idx, models in enumerate(model_lists):
  152. if models is not None and "error" not in models:
  153. merged_list.extend(
  154. [
  155. {
  156. **model,
  157. "name": model.get("name", model["id"]),
  158. "owned_by": "openai",
  159. "openai": model,
  160. "urlIdx": idx,
  161. }
  162. for model in models
  163. if "api.openai.com"
  164. not in app.state.config.OPENAI_API_BASE_URLS[idx]
  165. or "gpt" in model["id"]
  166. ]
  167. )
  168. return merged_list
  169. async def get_all_models():
  170. log.info("get_all_models()")
  171. if (
  172. len(app.state.config.OPENAI_API_KEYS) == 1
  173. and app.state.config.OPENAI_API_KEYS[0] == ""
  174. ) or not app.state.config.ENABLE_OPENAI_API:
  175. models = {"data": []}
  176. else:
  177. tasks = [
  178. fetch_url(f"{url}/models", app.state.config.OPENAI_API_KEYS[idx])
  179. for idx, url in enumerate(app.state.config.OPENAI_API_BASE_URLS)
  180. ]
  181. responses = await asyncio.gather(*tasks)
  182. log.debug(f"get_all_models:responses() {responses}")
  183. models = {
  184. "data": merge_models_lists(
  185. list(
  186. map(
  187. lambda response: (
  188. response["data"]
  189. if (response and "data" in response)
  190. else (response if isinstance(response, list) else None)
  191. ),
  192. responses,
  193. )
  194. )
  195. )
  196. }
  197. log.debug(f"models: {models}")
  198. app.state.MODELS = {model["id"]: model for model in models["data"]}
  199. return models
  200. @app.get("/models")
  201. @app.get("/models/{url_idx}")
  202. async def get_models(url_idx: Optional[int] = None, user=Depends(get_current_user)):
  203. if url_idx == None:
  204. models = await get_all_models()
  205. if app.state.config.ENABLE_MODEL_FILTER:
  206. if user.role == "user":
  207. models["data"] = list(
  208. filter(
  209. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  210. models["data"],
  211. )
  212. )
  213. return models
  214. return models
  215. else:
  216. url = app.state.config.OPENAI_API_BASE_URLS[url_idx]
  217. key = app.state.config.OPENAI_API_KEYS[url_idx]
  218. headers = {}
  219. headers["Authorization"] = f"Bearer {key}"
  220. headers["Content-Type"] = "application/json"
  221. r = None
  222. try:
  223. r = requests.request(method="GET", url=f"{url}/models", headers=headers)
  224. r.raise_for_status()
  225. response_data = r.json()
  226. if "api.openai.com" in url:
  227. response_data["data"] = list(
  228. filter(lambda model: "gpt" in model["id"], response_data["data"])
  229. )
  230. return response_data
  231. except Exception as e:
  232. log.exception(e)
  233. error_detail = "Open WebUI: Server Connection Error"
  234. if r is not None:
  235. try:
  236. res = r.json()
  237. if "error" in res:
  238. error_detail = f"External: {res['error']}"
  239. except:
  240. error_detail = f"External: {e}"
  241. raise HTTPException(
  242. status_code=r.status_code if r else 500,
  243. detail=error_detail,
  244. )
  245. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  246. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  247. idx = 0
  248. body = await request.body()
  249. # TODO: Remove below after gpt-4-vision fix from Open AI
  250. # Try to decode the body of the request from bytes to a UTF-8 string (Require add max_token to fix gpt-4-vision)
  251. payload = None
  252. try:
  253. if "chat/completions" in path:
  254. body = body.decode("utf-8")
  255. body = json.loads(body)
  256. payload = {**body}
  257. model_id = body.get("model")
  258. model_info = Models.get_model_by_id(model_id)
  259. if model_info:
  260. print(model_info)
  261. if model_info.base_model_id:
  262. payload["model"] = model_info.base_model_id
  263. model_info.params = model_info.params.model_dump()
  264. if model_info.params:
  265. payload["temperature"] = model_info.params.get("temperature", None)
  266. payload["top_p"] = model_info.params.get("top_p", None)
  267. payload["max_tokens"] = model_info.params.get("max_tokens", None)
  268. payload["frequency_penalty"] = model_info.params.get(
  269. "frequency_penalty", None
  270. )
  271. payload["seed"] = model_info.params.get("seed", None)
  272. payload["stop"] = (
  273. [
  274. bytes(stop, "utf-8").decode("unicode_escape")
  275. for stop in model_info.params["stop"]
  276. ]
  277. if model_info.params.get("stop", None)
  278. else None
  279. )
  280. if model_info.params.get("system", None):
  281. # Check if the payload already has a system message
  282. # If not, add a system message to the payload
  283. if payload.get("messages"):
  284. for message in payload["messages"]:
  285. if message.get("role") == "system":
  286. message["content"] = (
  287. model_info.params.get("system", None)
  288. + message["content"]
  289. )
  290. break
  291. else:
  292. payload["messages"].insert(
  293. 0,
  294. {
  295. "role": "system",
  296. "content": model_info.params.get("system", None),
  297. },
  298. )
  299. else:
  300. pass
  301. print(app.state.MODELS)
  302. model = app.state.MODELS[payload.get("model")]
  303. idx = model["urlIdx"]
  304. if "pipeline" in model and model.get("pipeline"):
  305. payload["user"] = {"name": user.name, "id": user.id}
  306. payload["title"] = (
  307. True
  308. if payload["stream"] == False and payload["max_tokens"] == 50
  309. else False
  310. )
  311. # Check if the model is "gpt-4-vision-preview" and set "max_tokens" to 4000
  312. # This is a workaround until OpenAI fixes the issue with this model
  313. if payload.get("model") == "gpt-4-vision-preview":
  314. if "max_tokens" not in payload:
  315. payload["max_tokens"] = 4000
  316. log.debug("Modified payload:", payload)
  317. # Convert the modified body back to JSON
  318. payload = json.dumps(payload)
  319. except json.JSONDecodeError as e:
  320. log.error("Error loading request body into a dictionary:", e)
  321. print(payload)
  322. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  323. key = app.state.config.OPENAI_API_KEYS[idx]
  324. target_url = f"{url}/{path}"
  325. headers = {}
  326. headers["Authorization"] = f"Bearer {key}"
  327. headers["Content-Type"] = "application/json"
  328. r = None
  329. try:
  330. r = requests.request(
  331. method=request.method,
  332. url=target_url,
  333. data=payload if payload else body,
  334. headers=headers,
  335. stream=True,
  336. )
  337. r.raise_for_status()
  338. # Check if response is SSE
  339. if "text/event-stream" in r.headers.get("Content-Type", ""):
  340. return StreamingResponse(
  341. r.iter_content(chunk_size=8192),
  342. status_code=r.status_code,
  343. headers=dict(r.headers),
  344. )
  345. else:
  346. response_data = r.json()
  347. return response_data
  348. except Exception as e:
  349. log.exception(e)
  350. error_detail = "Open WebUI: Server Connection Error"
  351. if r is not None:
  352. try:
  353. res = r.json()
  354. if "error" in res:
  355. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  356. except:
  357. error_detail = f"External: {e}"
  358. raise HTTPException(
  359. status_code=r.status_code if r else 500, detail=error_detail
  360. )