main.py 12 KB

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