main.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. merged_list.extend(
  129. [
  130. {**model, "urlIdx": idx}
  131. for model in models
  132. if "api.openai.com" not in app.state.OPENAI_API_BASE_URLS[idx]
  133. or "gpt" in model["id"]
  134. ]
  135. )
  136. return merged_list
  137. async def get_all_models():
  138. print("get_all_models")
  139. if len(app.state.OPENAI_API_KEYS) == 1 and app.state.OPENAI_API_KEYS[0] == "":
  140. models = {"data": []}
  141. else:
  142. tasks = [
  143. fetch_url(f"{url}/models", app.state.OPENAI_API_KEYS[idx])
  144. for idx, url in enumerate(app.state.OPENAI_API_BASE_URLS)
  145. ]
  146. responses = await asyncio.gather(*tasks)
  147. responses = list(
  148. filter(lambda x: x is not None and "error" not in x, responses)
  149. )
  150. models = {
  151. "data": merge_models_lists(
  152. list(map(lambda response: response["data"], responses))
  153. )
  154. }
  155. app.state.MODELS = {model["id"]: model for model in models["data"]}
  156. return models
  157. @app.get("/models")
  158. @app.get("/models/{url_idx}")
  159. async def get_models(url_idx: Optional[int] = None, user=Depends(get_current_user)):
  160. if url_idx == None:
  161. models = await get_all_models()
  162. if app.state.MODEL_FILTER_ENABLED:
  163. if user.role == "user":
  164. models["data"] = list(
  165. filter(
  166. lambda model: model["id"] in app.state.MODEL_FILTER_LIST,
  167. models["data"],
  168. )
  169. )
  170. return models
  171. return models
  172. else:
  173. url = app.state.OPENAI_API_BASE_URLS[url_idx]
  174. r = None
  175. try:
  176. r = requests.request(method="GET", url=f"{url}/models")
  177. r.raise_for_status()
  178. response_data = r.json()
  179. if "api.openai.com" in url:
  180. response_data["data"] = list(
  181. filter(lambda model: "gpt" in model["id"], response_data["data"])
  182. )
  183. return response_data
  184. except Exception as e:
  185. print(e)
  186. error_detail = "Open WebUI: Server Connection Error"
  187. if r is not None:
  188. try:
  189. res = r.json()
  190. if "error" in res:
  191. error_detail = f"External: {res['error']}"
  192. except:
  193. error_detail = f"External: {e}"
  194. raise HTTPException(
  195. status_code=r.status_code if r else 500,
  196. detail=error_detail,
  197. )
  198. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  199. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  200. idx = 0
  201. body = await request.body()
  202. # TODO: Remove below after gpt-4-vision fix from Open AI
  203. # Try to decode the body of the request from bytes to a UTF-8 string (Require add max_token to fix gpt-4-vision)
  204. try:
  205. body = body.decode("utf-8")
  206. body = json.loads(body)
  207. idx = app.state.MODELS[body.get("model")]["urlIdx"]
  208. # Check if the model is "gpt-4-vision-preview" and set "max_tokens" to 4000
  209. # This is a workaround until OpenAI fixes the issue with this model
  210. if body.get("model") == "gpt-4-vision-preview":
  211. if "max_tokens" not in body:
  212. body["max_tokens"] = 4000
  213. print("Modified body_dict:", body)
  214. # Fix for ChatGPT calls failing because the num_ctx key is in body
  215. if "num_ctx" in body:
  216. # If 'num_ctx' is in the dictionary, delete it
  217. # Leaving it there generates an error with the
  218. # OpenAI API (Feb 2024)
  219. del body["num_ctx"]
  220. # Convert the modified body back to JSON
  221. body = json.dumps(body)
  222. except json.JSONDecodeError as e:
  223. print("Error loading request body into a dictionary:", e)
  224. url = app.state.OPENAI_API_BASE_URLS[idx]
  225. key = app.state.OPENAI_API_KEYS[idx]
  226. target_url = f"{url}/{path}"
  227. if key == "":
  228. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
  229. headers = {}
  230. headers["Authorization"] = f"Bearer {key}"
  231. headers["Content-Type"] = "application/json"
  232. r = None
  233. try:
  234. r = requests.request(
  235. method=request.method,
  236. url=target_url,
  237. data=body,
  238. headers=headers,
  239. stream=True,
  240. )
  241. r.raise_for_status()
  242. # Check if response is SSE
  243. if "text/event-stream" in r.headers.get("Content-Type", ""):
  244. return StreamingResponse(
  245. r.iter_content(chunk_size=8192),
  246. status_code=r.status_code,
  247. headers=dict(r.headers),
  248. )
  249. else:
  250. response_data = r.json()
  251. return response_data
  252. except Exception as e:
  253. print(e)
  254. error_detail = "Open WebUI: Server Connection Error"
  255. if r is not None:
  256. try:
  257. res = r.json()
  258. if "error" in res:
  259. error_detail = f"External: {res['error']}"
  260. except:
  261. error_detail = f"External: {e}"
  262. raise HTTPException(
  263. status_code=r.status_code if r else 500, detail=error_detail
  264. )