openai.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. import asyncio
  2. import hashlib
  3. import json
  4. import logging
  5. from pathlib import Path
  6. from typing import Literal, Optional, overload
  7. import aiohttp
  8. from aiocache import cached
  9. import requests
  10. from fastapi import Depends, FastAPI, HTTPException, Request, APIRouter
  11. from fastapi.middleware.cors import CORSMiddleware
  12. from fastapi.responses import FileResponse, StreamingResponse
  13. from pydantic import BaseModel
  14. from starlette.background import BackgroundTask
  15. from open_webui.models.models import Models
  16. from open_webui.config import (
  17. CACHE_DIR,
  18. )
  19. from open_webui.env import (
  20. AIOHTTP_CLIENT_TIMEOUT,
  21. AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST,
  22. ENABLE_FORWARD_USER_INFO_HEADERS,
  23. BYPASS_MODEL_ACCESS_CONTROL,
  24. )
  25. from open_webui.models.users import UserModel
  26. from open_webui.constants import ERROR_MESSAGES
  27. from open_webui.env import ENV, SRC_LOG_LEVELS
  28. from open_webui.utils.payload import (
  29. apply_model_params_to_body_openai,
  30. apply_model_system_prompt_to_body,
  31. )
  32. from open_webui.utils.auth import get_admin_user, get_verified_user
  33. from open_webui.utils.access_control import has_access
  34. log = logging.getLogger(__name__)
  35. log.setLevel(SRC_LOG_LEVELS["OPENAI"])
  36. ##########################################
  37. #
  38. # Utility functions
  39. #
  40. ##########################################
  41. async def send_get_request(url, key=None, user: UserModel = None):
  42. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
  43. try:
  44. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  45. async with session.get(
  46. url,
  47. headers={
  48. **({"Authorization": f"Bearer {key}"} if key else {}),
  49. **(
  50. {
  51. "X-OpenWebUI-User-Name": user.name,
  52. "X-OpenWebUI-User-Id": user.id,
  53. "X-OpenWebUI-User-Email": user.email,
  54. "X-OpenWebUI-User-Role": user.role,
  55. }
  56. if ENABLE_FORWARD_USER_INFO_HEADERS and user
  57. else {}
  58. ),
  59. },
  60. ) as response:
  61. return await response.json()
  62. except Exception as e:
  63. # Handle connection error here
  64. log.error(f"Connection error: {e}")
  65. return None
  66. async def cleanup_response(
  67. response: Optional[aiohttp.ClientResponse],
  68. session: Optional[aiohttp.ClientSession],
  69. ):
  70. if response:
  71. response.close()
  72. if session:
  73. await session.close()
  74. def openai_o1_o3_handler(payload):
  75. """
  76. Handle o1, o3 specific parameters
  77. """
  78. if "max_tokens" in payload:
  79. # Remove "max_tokens" from the payload
  80. payload["max_completion_tokens"] = payload["max_tokens"]
  81. del payload["max_tokens"]
  82. # Fix: o1 and o3 do not support the "system" role directly.
  83. # For older models like "o1-mini" or "o1-preview", use role "user".
  84. # For newer o1/o3 models, replace "system" with "developer".
  85. if payload["messages"][0]["role"] == "system":
  86. model_lower = payload["model"].lower()
  87. if model_lower.startswith("o1-mini") or model_lower.startswith("o1-preview"):
  88. payload["messages"][0]["role"] = "user"
  89. else:
  90. payload["messages"][0]["role"] = "developer"
  91. return payload
  92. ##########################################
  93. #
  94. # API routes
  95. #
  96. ##########################################
  97. router = APIRouter()
  98. @router.get("/config")
  99. async def get_config(request: Request, user=Depends(get_admin_user)):
  100. return {
  101. "ENABLE_OPENAI_API": request.app.state.config.ENABLE_OPENAI_API,
  102. "OPENAI_API_BASE_URLS": request.app.state.config.OPENAI_API_BASE_URLS,
  103. "OPENAI_API_KEYS": request.app.state.config.OPENAI_API_KEYS,
  104. "OPENAI_API_CONFIGS": request.app.state.config.OPENAI_API_CONFIGS,
  105. }
  106. class OpenAIConfigForm(BaseModel):
  107. ENABLE_OPENAI_API: Optional[bool] = None
  108. OPENAI_API_BASE_URLS: list[str]
  109. OPENAI_API_KEYS: list[str]
  110. OPENAI_API_CONFIGS: dict
  111. @router.post("/config/update")
  112. async def update_config(
  113. request: Request, form_data: OpenAIConfigForm, user=Depends(get_admin_user)
  114. ):
  115. request.app.state.config.ENABLE_OPENAI_API = form_data.ENABLE_OPENAI_API
  116. request.app.state.config.OPENAI_API_BASE_URLS = form_data.OPENAI_API_BASE_URLS
  117. request.app.state.config.OPENAI_API_KEYS = form_data.OPENAI_API_KEYS
  118. # Check if API KEYS length is same than API URLS length
  119. if len(request.app.state.config.OPENAI_API_KEYS) != len(
  120. request.app.state.config.OPENAI_API_BASE_URLS
  121. ):
  122. if len(request.app.state.config.OPENAI_API_KEYS) > len(
  123. request.app.state.config.OPENAI_API_BASE_URLS
  124. ):
  125. request.app.state.config.OPENAI_API_KEYS = (
  126. request.app.state.config.OPENAI_API_KEYS[
  127. : len(request.app.state.config.OPENAI_API_BASE_URLS)
  128. ]
  129. )
  130. else:
  131. request.app.state.config.OPENAI_API_KEYS += [""] * (
  132. len(request.app.state.config.OPENAI_API_BASE_URLS)
  133. - len(request.app.state.config.OPENAI_API_KEYS)
  134. )
  135. request.app.state.config.OPENAI_API_CONFIGS = form_data.OPENAI_API_CONFIGS
  136. # Remove the API configs that are not in the API URLS
  137. keys = list(map(str, range(len(request.app.state.config.OPENAI_API_BASE_URLS))))
  138. request.app.state.config.OPENAI_API_CONFIGS = {
  139. key: value
  140. for key, value in request.app.state.config.OPENAI_API_CONFIGS.items()
  141. if key in keys
  142. }
  143. return {
  144. "ENABLE_OPENAI_API": request.app.state.config.ENABLE_OPENAI_API,
  145. "OPENAI_API_BASE_URLS": request.app.state.config.OPENAI_API_BASE_URLS,
  146. "OPENAI_API_KEYS": request.app.state.config.OPENAI_API_KEYS,
  147. "OPENAI_API_CONFIGS": request.app.state.config.OPENAI_API_CONFIGS,
  148. }
  149. @router.post("/audio/speech")
  150. async def speech(request: Request, user=Depends(get_verified_user)):
  151. idx = None
  152. try:
  153. idx = request.app.state.config.OPENAI_API_BASE_URLS.index(
  154. "https://api.openai.com/v1"
  155. )
  156. body = await request.body()
  157. name = hashlib.sha256(body).hexdigest()
  158. SPEECH_CACHE_DIR = CACHE_DIR / "audio" / "speech"
  159. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  160. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  161. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  162. # Check if the file already exists in the cache
  163. if file_path.is_file():
  164. return FileResponse(file_path)
  165. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  166. r = None
  167. try:
  168. r = requests.post(
  169. url=f"{url}/audio/speech",
  170. data=body,
  171. headers={
  172. "Content-Type": "application/json",
  173. "Authorization": f"Bearer {request.app.state.config.OPENAI_API_KEYS[idx]}",
  174. **(
  175. {
  176. "HTTP-Referer": "https://openwebui.com/",
  177. "X-Title": "Open WebUI",
  178. }
  179. if "openrouter.ai" in url
  180. else {}
  181. ),
  182. **(
  183. {
  184. "X-OpenWebUI-User-Name": user.name,
  185. "X-OpenWebUI-User-Id": user.id,
  186. "X-OpenWebUI-User-Email": user.email,
  187. "X-OpenWebUI-User-Role": user.role,
  188. }
  189. if ENABLE_FORWARD_USER_INFO_HEADERS
  190. else {}
  191. ),
  192. },
  193. stream=True,
  194. )
  195. r.raise_for_status()
  196. # Save the streaming content to a file
  197. with open(file_path, "wb") as f:
  198. for chunk in r.iter_content(chunk_size=8192):
  199. f.write(chunk)
  200. with open(file_body_path, "w") as f:
  201. json.dump(json.loads(body.decode("utf-8")), f)
  202. # Return the saved file
  203. return FileResponse(file_path)
  204. except Exception as e:
  205. log.exception(e)
  206. detail = None
  207. if r is not None:
  208. try:
  209. res = r.json()
  210. if "error" in res:
  211. detail = f"External: {res['error']}"
  212. except Exception:
  213. detail = f"External: {e}"
  214. raise HTTPException(
  215. status_code=r.status_code if r else 500,
  216. detail=detail if detail else "Open WebUI: Server Connection Error",
  217. )
  218. except ValueError:
  219. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.OPENAI_NOT_FOUND)
  220. async def get_all_models_responses(request: Request, user: UserModel) -> list:
  221. if not request.app.state.config.ENABLE_OPENAI_API:
  222. return []
  223. # Check if API KEYS length is same than API URLS length
  224. num_urls = len(request.app.state.config.OPENAI_API_BASE_URLS)
  225. num_keys = len(request.app.state.config.OPENAI_API_KEYS)
  226. if num_keys != num_urls:
  227. # if there are more keys than urls, remove the extra keys
  228. if num_keys > num_urls:
  229. new_keys = request.app.state.config.OPENAI_API_KEYS[:num_urls]
  230. request.app.state.config.OPENAI_API_KEYS = new_keys
  231. # if there are more urls than keys, add empty keys
  232. else:
  233. request.app.state.config.OPENAI_API_KEYS += [""] * (num_urls - num_keys)
  234. request_tasks = []
  235. for idx, url in enumerate(request.app.state.config.OPENAI_API_BASE_URLS):
  236. if (str(idx) not in request.app.state.config.OPENAI_API_CONFIGS) and (
  237. url not in request.app.state.config.OPENAI_API_CONFIGS # Legacy support
  238. ):
  239. request_tasks.append(
  240. send_get_request(
  241. f"{url}/models",
  242. request.app.state.config.OPENAI_API_KEYS[idx],
  243. user=user,
  244. )
  245. )
  246. else:
  247. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  248. str(idx),
  249. request.app.state.config.OPENAI_API_CONFIGS.get(
  250. url, {}
  251. ), # Legacy support
  252. )
  253. enable = api_config.get("enable", True)
  254. model_ids = api_config.get("model_ids", [])
  255. if enable:
  256. if len(model_ids) == 0:
  257. request_tasks.append(
  258. send_get_request(
  259. f"{url}/models",
  260. request.app.state.config.OPENAI_API_KEYS[idx],
  261. user=user,
  262. )
  263. )
  264. else:
  265. model_list = {
  266. "object": "list",
  267. "data": [
  268. {
  269. "id": model_id,
  270. "name": model_id,
  271. "owned_by": "openai",
  272. "openai": {"id": model_id},
  273. "urlIdx": idx,
  274. }
  275. for model_id in model_ids
  276. ],
  277. }
  278. request_tasks.append(
  279. asyncio.ensure_future(asyncio.sleep(0, model_list))
  280. )
  281. else:
  282. request_tasks.append(asyncio.ensure_future(asyncio.sleep(0, None)))
  283. responses = await asyncio.gather(*request_tasks)
  284. for idx, response in enumerate(responses):
  285. if response:
  286. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  287. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  288. str(idx),
  289. request.app.state.config.OPENAI_API_CONFIGS.get(
  290. url, {}
  291. ), # Legacy support
  292. )
  293. prefix_id = api_config.get("prefix_id", None)
  294. if prefix_id:
  295. for model in (
  296. response if isinstance(response, list) else response.get("data", [])
  297. ):
  298. model["id"] = f"{prefix_id}.{model['id']}"
  299. log.debug(f"get_all_models:responses() {responses}")
  300. return responses
  301. async def get_filtered_models(models, user):
  302. # Filter models based on user access control
  303. filtered_models = []
  304. for model in models.get("data", []):
  305. model_info = Models.get_model_by_id(model["id"])
  306. if model_info:
  307. if user.id == model_info.user_id or has_access(
  308. user.id, type="read", access_control=model_info.access_control
  309. ):
  310. filtered_models.append(model)
  311. return filtered_models
  312. @cached(ttl=3)
  313. async def get_all_models(request: Request, user: UserModel) -> dict[str, list]:
  314. log.info("get_all_models()")
  315. if not request.app.state.config.ENABLE_OPENAI_API:
  316. return {"data": []}
  317. responses = await get_all_models_responses(request, user=user)
  318. def extract_data(response):
  319. if response and "data" in response:
  320. return response["data"]
  321. if isinstance(response, list):
  322. return response
  323. return None
  324. def merge_models_lists(model_lists):
  325. log.debug(f"merge_models_lists {model_lists}")
  326. merged_list = []
  327. for idx, models in enumerate(model_lists):
  328. if models is not None and "error" not in models:
  329. merged_list.extend(
  330. [
  331. {
  332. **model,
  333. "name": model.get("name", model["id"]),
  334. "owned_by": "openai",
  335. "openai": model,
  336. "urlIdx": idx,
  337. }
  338. for model in models
  339. if "api.openai.com"
  340. not in request.app.state.config.OPENAI_API_BASE_URLS[idx]
  341. or not any(
  342. name in model["id"]
  343. for name in [
  344. "babbage",
  345. "dall-e",
  346. "davinci",
  347. "embedding",
  348. "tts",
  349. "whisper",
  350. ]
  351. )
  352. ]
  353. )
  354. return merged_list
  355. models = {"data": merge_models_lists(map(extract_data, responses))}
  356. log.debug(f"models: {models}")
  357. request.app.state.OPENAI_MODELS = {model["id"]: model for model in models["data"]}
  358. return models
  359. @router.get("/models")
  360. @router.get("/models/{url_idx}")
  361. async def get_models(
  362. request: Request, url_idx: Optional[int] = None, user=Depends(get_verified_user)
  363. ):
  364. models = {
  365. "data": [],
  366. }
  367. if url_idx is None:
  368. models = await get_all_models(request, user=user)
  369. else:
  370. url = request.app.state.config.OPENAI_API_BASE_URLS[url_idx]
  371. key = request.app.state.config.OPENAI_API_KEYS[url_idx]
  372. r = None
  373. async with aiohttp.ClientSession(
  374. timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
  375. ) as session:
  376. try:
  377. async with session.get(
  378. f"{url}/models",
  379. headers={
  380. "Authorization": f"Bearer {key}",
  381. "Content-Type": "application/json",
  382. **(
  383. {
  384. "X-OpenWebUI-User-Name": user.name,
  385. "X-OpenWebUI-User-Id": user.id,
  386. "X-OpenWebUI-User-Email": user.email,
  387. "X-OpenWebUI-User-Role": user.role,
  388. }
  389. if ENABLE_FORWARD_USER_INFO_HEADERS
  390. else {}
  391. ),
  392. },
  393. ) as r:
  394. if r.status != 200:
  395. # Extract response error details if available
  396. error_detail = f"HTTP Error: {r.status}"
  397. res = await r.json()
  398. if "error" in res:
  399. error_detail = f"External Error: {res['error']}"
  400. raise Exception(error_detail)
  401. response_data = await r.json()
  402. # Check if we're calling OpenAI API based on the URL
  403. if "api.openai.com" in url:
  404. # Filter models according to the specified conditions
  405. response_data["data"] = [
  406. model
  407. for model in response_data.get("data", [])
  408. if not any(
  409. name in model["id"]
  410. for name in [
  411. "babbage",
  412. "dall-e",
  413. "davinci",
  414. "embedding",
  415. "tts",
  416. "whisper",
  417. ]
  418. )
  419. ]
  420. models = response_data
  421. except aiohttp.ClientError as e:
  422. # ClientError covers all aiohttp requests issues
  423. log.exception(f"Client error: {str(e)}")
  424. raise HTTPException(
  425. status_code=500, detail="Open WebUI: Server Connection Error"
  426. )
  427. except Exception as e:
  428. log.exception(f"Unexpected error: {e}")
  429. error_detail = f"Unexpected error: {str(e)}"
  430. raise HTTPException(status_code=500, detail=error_detail)
  431. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  432. models["data"] = await get_filtered_models(models, user)
  433. return models
  434. class ConnectionVerificationForm(BaseModel):
  435. url: str
  436. key: str
  437. @router.post("/verify")
  438. async def verify_connection(
  439. form_data: ConnectionVerificationForm, user=Depends(get_admin_user)
  440. ):
  441. url = form_data.url
  442. key = form_data.key
  443. async with aiohttp.ClientSession(
  444. timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
  445. ) as session:
  446. try:
  447. async with session.get(
  448. f"{url}/models",
  449. headers={
  450. "Authorization": f"Bearer {key}",
  451. "Content-Type": "application/json",
  452. **(
  453. {
  454. "X-OpenWebUI-User-Name": user.name,
  455. "X-OpenWebUI-User-Id": user.id,
  456. "X-OpenWebUI-User-Email": user.email,
  457. "X-OpenWebUI-User-Role": user.role,
  458. }
  459. if ENABLE_FORWARD_USER_INFO_HEADERS
  460. else {}
  461. ),
  462. },
  463. ) as r:
  464. if r.status != 200:
  465. # Extract response error details if available
  466. error_detail = f"HTTP Error: {r.status}"
  467. res = await r.json()
  468. if "error" in res:
  469. error_detail = f"External Error: {res['error']}"
  470. raise Exception(error_detail)
  471. response_data = await r.json()
  472. return response_data
  473. except aiohttp.ClientError as e:
  474. # ClientError covers all aiohttp requests issues
  475. log.exception(f"Client error: {str(e)}")
  476. raise HTTPException(
  477. status_code=500, detail="Open WebUI: Server Connection Error"
  478. )
  479. except Exception as e:
  480. log.exception(f"Unexpected error: {e}")
  481. error_detail = f"Unexpected error: {str(e)}"
  482. raise HTTPException(status_code=500, detail=error_detail)
  483. @router.post("/chat/completions")
  484. async def generate_chat_completion(
  485. request: Request,
  486. form_data: dict,
  487. user=Depends(get_verified_user),
  488. bypass_filter: Optional[bool] = False,
  489. ):
  490. if BYPASS_MODEL_ACCESS_CONTROL:
  491. bypass_filter = True
  492. idx = 0
  493. payload = {**form_data}
  494. metadata = payload.pop("metadata", None)
  495. model_id = form_data.get("model")
  496. model_info = Models.get_model_by_id(model_id)
  497. # Check model info and override the payload
  498. if model_info:
  499. if model_info.base_model_id:
  500. payload["model"] = model_info.base_model_id
  501. model_id = model_info.base_model_id
  502. params = model_info.params.model_dump()
  503. payload = apply_model_params_to_body_openai(params, payload)
  504. payload = apply_model_system_prompt_to_body(params, payload, metadata, user)
  505. # Check if user has access to the model
  506. if not bypass_filter and user.role == "user":
  507. if not (
  508. user.id == model_info.user_id
  509. or has_access(
  510. user.id, type="read", access_control=model_info.access_control
  511. )
  512. ):
  513. raise HTTPException(
  514. status_code=403,
  515. detail="Model not found",
  516. )
  517. elif not bypass_filter:
  518. if user.role != "admin":
  519. raise HTTPException(
  520. status_code=403,
  521. detail="Model not found",
  522. )
  523. await get_all_models(request, user=user)
  524. model = request.app.state.OPENAI_MODELS.get(model_id)
  525. if model:
  526. idx = model["urlIdx"]
  527. else:
  528. raise HTTPException(
  529. status_code=404,
  530. detail="Model not found",
  531. )
  532. # Get the API config for the model
  533. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  534. str(idx),
  535. request.app.state.config.OPENAI_API_CONFIGS.get(
  536. request.app.state.config.OPENAI_API_BASE_URLS[idx], {}
  537. ), # Legacy support
  538. )
  539. prefix_id = api_config.get("prefix_id", None)
  540. if prefix_id:
  541. payload["model"] = payload["model"].replace(f"{prefix_id}.", "")
  542. # Add user info to the payload if the model is a pipeline
  543. if "pipeline" in model and model.get("pipeline"):
  544. payload["user"] = {
  545. "name": user.name,
  546. "id": user.id,
  547. "email": user.email,
  548. "role": user.role,
  549. }
  550. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  551. key = request.app.state.config.OPENAI_API_KEYS[idx]
  552. # Fix: o1,o3 does not support the "max_tokens" parameter, Modify "max_tokens" to "max_completion_tokens"
  553. is_o1_o3 = payload["model"].lower().startswith(("o1", "o3-"))
  554. if is_o1_o3:
  555. payload = openai_o1_o3_handler(payload)
  556. elif "api.openai.com" not in url:
  557. # Remove "max_completion_tokens" from the payload for backward compatibility
  558. if "max_completion_tokens" in payload:
  559. payload["max_tokens"] = payload["max_completion_tokens"]
  560. del payload["max_completion_tokens"]
  561. if "max_tokens" in payload and "max_completion_tokens" in payload:
  562. del payload["max_tokens"]
  563. # Convert the modified body back to JSON
  564. payload = json.dumps(payload)
  565. r = None
  566. session = None
  567. streaming = False
  568. response = None
  569. try:
  570. session = aiohttp.ClientSession(
  571. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  572. )
  573. r = await session.request(
  574. method="POST",
  575. url=f"{url}/chat/completions",
  576. data=payload,
  577. headers={
  578. "Authorization": f"Bearer {key}",
  579. "Content-Type": "application/json",
  580. **(
  581. {
  582. "HTTP-Referer": "https://openwebui.com/",
  583. "X-Title": "Open WebUI",
  584. }
  585. if "openrouter.ai" in url
  586. else {}
  587. ),
  588. **(
  589. {
  590. "X-OpenWebUI-User-Name": user.name,
  591. "X-OpenWebUI-User-Id": user.id,
  592. "X-OpenWebUI-User-Email": user.email,
  593. "X-OpenWebUI-User-Role": user.role,
  594. }
  595. if ENABLE_FORWARD_USER_INFO_HEADERS
  596. else {}
  597. ),
  598. },
  599. )
  600. # Check if response is SSE
  601. if "text/event-stream" in r.headers.get("Content-Type", ""):
  602. streaming = True
  603. return StreamingResponse(
  604. r.content,
  605. status_code=r.status,
  606. headers=dict(r.headers),
  607. background=BackgroundTask(
  608. cleanup_response, response=r, session=session
  609. ),
  610. )
  611. else:
  612. try:
  613. response = await r.json()
  614. except Exception as e:
  615. log.error(e)
  616. response = await r.text()
  617. r.raise_for_status()
  618. return response
  619. except Exception as e:
  620. log.exception(e)
  621. detail = None
  622. if isinstance(response, dict):
  623. if "error" in response:
  624. detail = f"{response['error']['message'] if 'message' in response['error'] else response['error']}"
  625. elif isinstance(response, str):
  626. detail = response
  627. raise HTTPException(
  628. status_code=r.status if r else 500,
  629. detail=detail if detail else "Open WebUI: Server Connection Error",
  630. )
  631. finally:
  632. if not streaming and session:
  633. if r:
  634. r.close()
  635. await session.close()
  636. @router.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  637. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  638. """
  639. Deprecated: proxy all requests to OpenAI API
  640. """
  641. body = await request.body()
  642. idx = 0
  643. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  644. key = request.app.state.config.OPENAI_API_KEYS[idx]
  645. r = None
  646. session = None
  647. streaming = False
  648. try:
  649. session = aiohttp.ClientSession(trust_env=True)
  650. r = await session.request(
  651. method=request.method,
  652. url=f"{url}/{path}",
  653. data=body,
  654. headers={
  655. "Authorization": f"Bearer {key}",
  656. "Content-Type": "application/json",
  657. **(
  658. {
  659. "X-OpenWebUI-User-Name": user.name,
  660. "X-OpenWebUI-User-Id": user.id,
  661. "X-OpenWebUI-User-Email": user.email,
  662. "X-OpenWebUI-User-Role": user.role,
  663. }
  664. if ENABLE_FORWARD_USER_INFO_HEADERS
  665. else {}
  666. ),
  667. },
  668. )
  669. r.raise_for_status()
  670. # Check if response is SSE
  671. if "text/event-stream" in r.headers.get("Content-Type", ""):
  672. streaming = True
  673. return StreamingResponse(
  674. r.content,
  675. status_code=r.status,
  676. headers=dict(r.headers),
  677. background=BackgroundTask(
  678. cleanup_response, response=r, session=session
  679. ),
  680. )
  681. else:
  682. response_data = await r.json()
  683. return response_data
  684. except Exception as e:
  685. log.exception(e)
  686. detail = None
  687. if r is not None:
  688. try:
  689. res = await r.json()
  690. log.error(res)
  691. if "error" in res:
  692. detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  693. except Exception:
  694. detail = f"External: {e}"
  695. raise HTTPException(
  696. status_code=r.status if r else 500,
  697. detail=detail if detail else "Open WebUI: Server Connection Error",
  698. )
  699. finally:
  700. if not streaming and session:
  701. if r:
  702. r.close()
  703. await session.close()