main.py 11 KB

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