main.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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 starlette.background import BackgroundTask
  11. from apps.webui.models.models import Models
  12. from apps.webui.models.users import Users
  13. from constants import ERROR_MESSAGES
  14. from utils.utils import (
  15. decode_token,
  16. get_verified_user,
  17. get_verified_user,
  18. get_admin_user,
  19. )
  20. from utils.task import prompt_template
  21. from utils.misc import add_or_update_system_message
  22. from config import (
  23. SRC_LOG_LEVELS,
  24. ENABLE_OPENAI_API,
  25. AIOHTTP_CLIENT_TIMEOUT,
  26. OPENAI_API_BASE_URLS,
  27. OPENAI_API_KEYS,
  28. CACHE_DIR,
  29. ENABLE_MODEL_FILTER,
  30. MODEL_FILTER_LIST,
  31. AppConfig,
  32. )
  33. from typing import List, Optional
  34. import hashlib
  35. from pathlib import Path
  36. log = logging.getLogger(__name__)
  37. log.setLevel(SRC_LOG_LEVELS["OPENAI"])
  38. app = FastAPI()
  39. app.add_middleware(
  40. CORSMiddleware,
  41. allow_origins=["*"],
  42. allow_credentials=True,
  43. allow_methods=["*"],
  44. allow_headers=["*"],
  45. )
  46. app.state.config = AppConfig()
  47. app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
  48. app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
  49. app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
  50. app.state.config.OPENAI_API_BASE_URLS = OPENAI_API_BASE_URLS
  51. app.state.config.OPENAI_API_KEYS = OPENAI_API_KEYS
  52. app.state.MODELS = {}
  53. @app.middleware("http")
  54. async def check_url(request: Request, call_next):
  55. if len(app.state.MODELS) == 0:
  56. await get_all_models()
  57. else:
  58. pass
  59. response = await call_next(request)
  60. return response
  61. @app.get("/config")
  62. async def get_config(user=Depends(get_admin_user)):
  63. return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
  64. class OpenAIConfigForm(BaseModel):
  65. enable_openai_api: Optional[bool] = None
  66. @app.post("/config/update")
  67. async def update_config(form_data: OpenAIConfigForm, user=Depends(get_admin_user)):
  68. app.state.config.ENABLE_OPENAI_API = form_data.enable_openai_api
  69. return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
  70. class UrlsUpdateForm(BaseModel):
  71. urls: List[str]
  72. class KeysUpdateForm(BaseModel):
  73. keys: List[str]
  74. @app.get("/urls")
  75. async def get_openai_urls(user=Depends(get_admin_user)):
  76. return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
  77. @app.post("/urls/update")
  78. async def update_openai_urls(form_data: UrlsUpdateForm, user=Depends(get_admin_user)):
  79. await get_all_models()
  80. app.state.config.OPENAI_API_BASE_URLS = form_data.urls
  81. return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
  82. @app.get("/keys")
  83. async def get_openai_keys(user=Depends(get_admin_user)):
  84. return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
  85. @app.post("/keys/update")
  86. async def update_openai_key(form_data: KeysUpdateForm, user=Depends(get_admin_user)):
  87. app.state.config.OPENAI_API_KEYS = form_data.keys
  88. return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
  89. @app.post("/audio/speech")
  90. async def speech(request: Request, user=Depends(get_verified_user)):
  91. idx = None
  92. try:
  93. idx = app.state.config.OPENAI_API_BASE_URLS.index("https://api.openai.com/v1")
  94. body = await request.body()
  95. name = hashlib.sha256(body).hexdigest()
  96. SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
  97. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  98. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  99. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  100. # Check if the file already exists in the cache
  101. if file_path.is_file():
  102. return FileResponse(file_path)
  103. headers = {}
  104. headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEYS[idx]}"
  105. headers["Content-Type"] = "application/json"
  106. if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
  107. headers["HTTP-Referer"] = "https://openwebui.com/"
  108. headers["X-Title"] = "Open WebUI"
  109. r = None
  110. try:
  111. r = requests.post(
  112. url=f"{app.state.config.OPENAI_API_BASE_URLS[idx]}/audio/speech",
  113. data=body,
  114. headers=headers,
  115. stream=True,
  116. )
  117. r.raise_for_status()
  118. # Save the streaming content to a file
  119. with open(file_path, "wb") as f:
  120. for chunk in r.iter_content(chunk_size=8192):
  121. f.write(chunk)
  122. with open(file_body_path, "w") as f:
  123. json.dump(json.loads(body.decode("utf-8")), f)
  124. # Return the saved file
  125. return FileResponse(file_path)
  126. except Exception as e:
  127. log.exception(e)
  128. error_detail = "Open WebUI: Server Connection Error"
  129. if r is not None:
  130. try:
  131. res = r.json()
  132. if "error" in res:
  133. error_detail = f"External: {res['error']}"
  134. except:
  135. error_detail = f"External: {e}"
  136. raise HTTPException(
  137. status_code=r.status_code if r else 500, detail=error_detail
  138. )
  139. except ValueError:
  140. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.OPENAI_NOT_FOUND)
  141. async def fetch_url(url, key):
  142. timeout = aiohttp.ClientTimeout(total=5)
  143. try:
  144. headers = {"Authorization": f"Bearer {key}"}
  145. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  146. async with session.get(url, headers=headers) as response:
  147. return await response.json()
  148. except Exception as e:
  149. # Handle connection error here
  150. log.error(f"Connection error: {e}")
  151. return None
  152. async def cleanup_response(
  153. response: Optional[aiohttp.ClientResponse],
  154. session: Optional[aiohttp.ClientSession],
  155. ):
  156. if response:
  157. response.close()
  158. if session:
  159. await session.close()
  160. def merge_models_lists(model_lists):
  161. log.debug(f"merge_models_lists {model_lists}")
  162. merged_list = []
  163. for idx, models in enumerate(model_lists):
  164. if models is not None and "error" not in models:
  165. merged_list.extend(
  166. [
  167. {
  168. **model,
  169. "name": model.get("name", model["id"]),
  170. "owned_by": "openai",
  171. "openai": model,
  172. "urlIdx": idx,
  173. }
  174. for model in models
  175. if "api.openai.com"
  176. not in app.state.config.OPENAI_API_BASE_URLS[idx]
  177. or "gpt" in model["id"]
  178. ]
  179. )
  180. return merged_list
  181. async def get_all_models(raw: bool = False):
  182. log.info("get_all_models()")
  183. if (
  184. len(app.state.config.OPENAI_API_KEYS) == 1
  185. and app.state.config.OPENAI_API_KEYS[0] == ""
  186. ) or not app.state.config.ENABLE_OPENAI_API:
  187. models = {"data": []}
  188. else:
  189. # Check if API KEYS length is same than API URLS length
  190. if len(app.state.config.OPENAI_API_KEYS) != len(
  191. app.state.config.OPENAI_API_BASE_URLS
  192. ):
  193. # if there are more keys than urls, remove the extra keys
  194. if len(app.state.config.OPENAI_API_KEYS) > len(
  195. app.state.config.OPENAI_API_BASE_URLS
  196. ):
  197. app.state.config.OPENAI_API_KEYS = app.state.config.OPENAI_API_KEYS[
  198. : len(app.state.config.OPENAI_API_BASE_URLS)
  199. ]
  200. # if there are more urls than keys, add empty keys
  201. else:
  202. app.state.config.OPENAI_API_KEYS += [
  203. ""
  204. for _ in range(
  205. len(app.state.config.OPENAI_API_BASE_URLS)
  206. - len(app.state.config.OPENAI_API_KEYS)
  207. )
  208. ]
  209. tasks = [
  210. fetch_url(f"{url}/models", app.state.config.OPENAI_API_KEYS[idx])
  211. for idx, url in enumerate(app.state.config.OPENAI_API_BASE_URLS)
  212. ]
  213. responses = await asyncio.gather(*tasks)
  214. log.debug(f"get_all_models:responses() {responses}")
  215. if raw:
  216. return responses
  217. models = {
  218. "data": merge_models_lists(
  219. list(
  220. map(
  221. lambda response: (
  222. response["data"]
  223. if (response and "data" in response)
  224. else (response if isinstance(response, list) else None)
  225. ),
  226. responses,
  227. )
  228. )
  229. )
  230. }
  231. log.debug(f"models: {models}")
  232. app.state.MODELS = {model["id"]: model for model in models["data"]}
  233. return models
  234. @app.get("/models")
  235. @app.get("/models/{url_idx}")
  236. async def get_models(url_idx: Optional[int] = None, user=Depends(get_verified_user)):
  237. if url_idx == None:
  238. models = await get_all_models()
  239. if app.state.config.ENABLE_MODEL_FILTER:
  240. if user.role == "user":
  241. models["data"] = list(
  242. filter(
  243. lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
  244. models["data"],
  245. )
  246. )
  247. return models
  248. return models
  249. else:
  250. url = app.state.config.OPENAI_API_BASE_URLS[url_idx]
  251. key = app.state.config.OPENAI_API_KEYS[url_idx]
  252. headers = {}
  253. headers["Authorization"] = f"Bearer {key}"
  254. headers["Content-Type"] = "application/json"
  255. r = None
  256. try:
  257. r = requests.request(method="GET", url=f"{url}/models", headers=headers)
  258. r.raise_for_status()
  259. response_data = r.json()
  260. if "api.openai.com" in url:
  261. response_data["data"] = list(
  262. filter(lambda model: "gpt" in model["id"], response_data["data"])
  263. )
  264. return response_data
  265. except Exception as e:
  266. log.exception(e)
  267. error_detail = "Open WebUI: Server Connection Error"
  268. if r is not None:
  269. try:
  270. res = r.json()
  271. if "error" in res:
  272. error_detail = f"External: {res['error']}"
  273. except:
  274. error_detail = f"External: {e}"
  275. raise HTTPException(
  276. status_code=r.status_code if r else 500,
  277. detail=error_detail,
  278. )
  279. @app.post("/chat/completions")
  280. @app.post("/chat/completions/{url_idx}")
  281. async def generate_chat_completion(
  282. form_data: dict,
  283. url_idx: Optional[int] = None,
  284. user=Depends(get_verified_user),
  285. ):
  286. idx = 0
  287. payload = {**form_data}
  288. if "metadata" in payload:
  289. del payload["metadata"]
  290. model_id = form_data.get("model")
  291. model_info = Models.get_model_by_id(model_id)
  292. if model_info:
  293. if model_info.base_model_id:
  294. payload["model"] = model_info.base_model_id
  295. model_info.params = model_info.params.model_dump()
  296. if model_info.params:
  297. if (
  298. model_info.params.get("temperature", None) is not None
  299. and payload.get("temperature") is None
  300. ):
  301. payload["temperature"] = float(model_info.params.get("temperature"))
  302. if model_info.params.get("top_p", None) and payload.get("top_p") is None:
  303. payload["top_p"] = int(model_info.params.get("top_p", None))
  304. if (
  305. model_info.params.get("max_tokens", None)
  306. and payload.get("max_tokens") is None
  307. ):
  308. payload["max_tokens"] = int(model_info.params.get("max_tokens", None))
  309. if (
  310. model_info.params.get("frequency_penalty", None)
  311. and payload.get("frequency_penalty") is None
  312. ):
  313. payload["frequency_penalty"] = int(
  314. model_info.params.get("frequency_penalty", None)
  315. )
  316. if (
  317. model_info.params.get("seed", None) is not None
  318. and payload.get("seed") is None
  319. ):
  320. payload["seed"] = model_info.params.get("seed", None)
  321. if model_info.params.get("stop", None) and payload.get("stop") is None:
  322. payload["stop"] = (
  323. [
  324. bytes(stop, "utf-8").decode("unicode_escape")
  325. for stop in model_info.params["stop"]
  326. ]
  327. if model_info.params.get("stop", None)
  328. else None
  329. )
  330. system = model_info.params.get("system", None)
  331. if system:
  332. system = prompt_template(
  333. system,
  334. **(
  335. {
  336. "user_name": user.name,
  337. "user_location": (
  338. user.info.get("location") if user.info else None
  339. ),
  340. }
  341. if user
  342. else {}
  343. ),
  344. )
  345. if payload.get("messages"):
  346. payload["messages"] = add_or_update_system_message(
  347. system, payload["messages"]
  348. )
  349. else:
  350. pass
  351. model = app.state.MODELS[payload.get("model")]
  352. idx = model["urlIdx"]
  353. if "pipeline" in model and model.get("pipeline"):
  354. payload["user"] = {
  355. "name": user.name,
  356. "id": user.id,
  357. "email": user.email,
  358. "role": user.role,
  359. }
  360. # Check if the model is "gpt-4-vision-preview" and set "max_tokens" to 4000
  361. # This is a workaround until OpenAI fixes the issue with this model
  362. if payload.get("model") == "gpt-4-vision-preview":
  363. if "max_tokens" not in payload:
  364. payload["max_tokens"] = 4000
  365. log.debug("Modified payload:", payload)
  366. # Convert the modified body back to JSON
  367. payload = json.dumps(payload)
  368. log.debug(payload)
  369. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  370. key = app.state.config.OPENAI_API_KEYS[idx]
  371. headers = {}
  372. headers["Authorization"] = f"Bearer {key}"
  373. headers["Content-Type"] = "application/json"
  374. r = None
  375. session = None
  376. streaming = False
  377. try:
  378. session = aiohttp.ClientSession(
  379. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  380. )
  381. r = await session.request(
  382. method="POST",
  383. url=f"{url}/chat/completions",
  384. data=payload,
  385. headers=headers,
  386. )
  387. r.raise_for_status()
  388. # Check if response is SSE
  389. if "text/event-stream" in r.headers.get("Content-Type", ""):
  390. streaming = True
  391. return StreamingResponse(
  392. r.content,
  393. status_code=r.status,
  394. headers=dict(r.headers),
  395. background=BackgroundTask(
  396. cleanup_response, response=r, session=session
  397. ),
  398. )
  399. else:
  400. response_data = await r.json()
  401. return response_data
  402. except Exception as e:
  403. log.exception(e)
  404. error_detail = "Open WebUI: Server Connection Error"
  405. if r is not None:
  406. try:
  407. res = await r.json()
  408. print(res)
  409. if "error" in res:
  410. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  411. except:
  412. error_detail = f"External: {e}"
  413. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  414. finally:
  415. if not streaming and session:
  416. if r:
  417. r.close()
  418. await session.close()
  419. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  420. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  421. idx = 0
  422. body = await request.body()
  423. url = app.state.config.OPENAI_API_BASE_URLS[idx]
  424. key = app.state.config.OPENAI_API_KEYS[idx]
  425. target_url = f"{url}/{path}"
  426. headers = {}
  427. headers["Authorization"] = f"Bearer {key}"
  428. headers["Content-Type"] = "application/json"
  429. r = None
  430. session = None
  431. streaming = False
  432. try:
  433. session = aiohttp.ClientSession(trust_env=True)
  434. r = await session.request(
  435. method=request.method,
  436. url=target_url,
  437. data=body,
  438. headers=headers,
  439. )
  440. r.raise_for_status()
  441. # Check if response is SSE
  442. if "text/event-stream" in r.headers.get("Content-Type", ""):
  443. streaming = True
  444. return StreamingResponse(
  445. r.content,
  446. status_code=r.status,
  447. headers=dict(r.headers),
  448. background=BackgroundTask(
  449. cleanup_response, response=r, session=session
  450. ),
  451. )
  452. else:
  453. response_data = await r.json()
  454. return response_data
  455. except Exception as e:
  456. log.exception(e)
  457. error_detail = "Open WebUI: Server Connection Error"
  458. if r is not None:
  459. try:
  460. res = await r.json()
  461. print(res)
  462. if "error" in res:
  463. error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  464. except:
  465. error_detail = f"External: {e}"
  466. raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
  467. finally:
  468. if not streaming and session:
  469. if r:
  470. r.close()
  471. await session.close()