main.py 11 KB

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