main.py 10 KB

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