main.py 9.4 KB

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