main.py 11 KB

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