main.py 9.0 KB

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