main.py 9.7 KB

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