main.py 12 KB

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