main.py 11 KB

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