main.py 18 KB

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