main.py 11 KB

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