openai.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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_OPENAI_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_OPENAI_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
  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 = Path(CACHE_DIR).joinpath("./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(
  375. total=AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST
  376. )
  377. ) as session:
  378. try:
  379. async with session.get(
  380. f"{url}/models",
  381. headers={
  382. "Authorization": f"Bearer {key}",
  383. "Content-Type": "application/json",
  384. **(
  385. {
  386. "X-OpenWebUI-User-Name": user.name,
  387. "X-OpenWebUI-User-Id": user.id,
  388. "X-OpenWebUI-User-Email": user.email,
  389. "X-OpenWebUI-User-Role": user.role,
  390. }
  391. if ENABLE_FORWARD_USER_INFO_HEADERS
  392. else {}
  393. ),
  394. },
  395. ) as r:
  396. if r.status != 200:
  397. # Extract response error details if available
  398. error_detail = f"HTTP Error: {r.status}"
  399. res = await r.json()
  400. if "error" in res:
  401. error_detail = f"External Error: {res['error']}"
  402. raise Exception(error_detail)
  403. response_data = await r.json()
  404. # Check if we're calling OpenAI API based on the URL
  405. if "api.openai.com" in url:
  406. # Filter models according to the specified conditions
  407. response_data["data"] = [
  408. model
  409. for model in response_data.get("data", [])
  410. if not any(
  411. name in model["id"]
  412. for name in [
  413. "babbage",
  414. "dall-e",
  415. "davinci",
  416. "embedding",
  417. "tts",
  418. "whisper",
  419. ]
  420. )
  421. ]
  422. models = response_data
  423. except aiohttp.ClientError as e:
  424. # ClientError covers all aiohttp requests issues
  425. log.exception(f"Client error: {str(e)}")
  426. raise HTTPException(
  427. status_code=500, detail="Open WebUI: Server Connection Error"
  428. )
  429. except Exception as e:
  430. log.exception(f"Unexpected error: {e}")
  431. error_detail = f"Unexpected error: {str(e)}"
  432. raise HTTPException(status_code=500, detail=error_detail)
  433. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  434. models["data"] = await get_filtered_models(models, user)
  435. return models
  436. class ConnectionVerificationForm(BaseModel):
  437. url: str
  438. key: str
  439. @router.post("/verify")
  440. async def verify_connection(
  441. form_data: ConnectionVerificationForm, user=Depends(get_admin_user)
  442. ):
  443. url = form_data.url
  444. key = form_data.key
  445. async with aiohttp.ClientSession(
  446. timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST)
  447. ) as session:
  448. try:
  449. async with session.get(
  450. f"{url}/models",
  451. headers={
  452. "Authorization": f"Bearer {key}",
  453. "Content-Type": "application/json",
  454. **(
  455. {
  456. "X-OpenWebUI-User-Name": user.name,
  457. "X-OpenWebUI-User-Id": user.id,
  458. "X-OpenWebUI-User-Email": user.email,
  459. "X-OpenWebUI-User-Role": user.role,
  460. }
  461. if ENABLE_FORWARD_USER_INFO_HEADERS
  462. else {}
  463. ),
  464. },
  465. ) as r:
  466. if r.status != 200:
  467. # Extract response error details if available
  468. error_detail = f"HTTP Error: {r.status}"
  469. res = await r.json()
  470. if "error" in res:
  471. error_detail = f"External Error: {res['error']}"
  472. raise Exception(error_detail)
  473. response_data = await r.json()
  474. return response_data
  475. except aiohttp.ClientError as e:
  476. # ClientError covers all aiohttp requests issues
  477. log.exception(f"Client error: {str(e)}")
  478. raise HTTPException(
  479. status_code=500, detail="Open WebUI: Server Connection Error"
  480. )
  481. except Exception as e:
  482. log.exception(f"Unexpected error: {e}")
  483. error_detail = f"Unexpected error: {str(e)}"
  484. raise HTTPException(status_code=500, detail=error_detail)
  485. @router.post("/chat/completions")
  486. async def generate_chat_completion(
  487. request: Request,
  488. form_data: dict,
  489. user=Depends(get_verified_user),
  490. bypass_filter: Optional[bool] = False,
  491. ):
  492. if BYPASS_MODEL_ACCESS_CONTROL:
  493. bypass_filter = True
  494. idx = 0
  495. payload = {**form_data}
  496. metadata = payload.pop("metadata", None)
  497. model_id = form_data.get("model")
  498. model_info = Models.get_model_by_id(model_id)
  499. # Check model info and override the payload
  500. if model_info:
  501. if model_info.base_model_id:
  502. payload["model"] = model_info.base_model_id
  503. model_id = model_info.base_model_id
  504. params = model_info.params.model_dump()
  505. payload = apply_model_params_to_body_openai(params, payload)
  506. payload = apply_model_system_prompt_to_body(params, payload, metadata, user)
  507. # Check if user has access to the model
  508. if not bypass_filter and user.role == "user":
  509. if not (
  510. user.id == model_info.user_id
  511. or has_access(
  512. user.id, type="read", access_control=model_info.access_control
  513. )
  514. ):
  515. raise HTTPException(
  516. status_code=403,
  517. detail="Model not found",
  518. )
  519. elif not bypass_filter:
  520. if user.role != "admin":
  521. raise HTTPException(
  522. status_code=403,
  523. detail="Model not found",
  524. )
  525. await get_all_models(request, user=user)
  526. model = request.app.state.OPENAI_MODELS.get(model_id)
  527. if model:
  528. idx = model["urlIdx"]
  529. else:
  530. raise HTTPException(
  531. status_code=404,
  532. detail="Model not found",
  533. )
  534. # Get the API config for the model
  535. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  536. str(idx),
  537. request.app.state.config.OPENAI_API_CONFIGS.get(
  538. request.app.state.config.OPENAI_API_BASE_URLS[idx], {}
  539. ), # Legacy support
  540. )
  541. prefix_id = api_config.get("prefix_id", None)
  542. if prefix_id:
  543. payload["model"] = payload["model"].replace(f"{prefix_id}.", "")
  544. # Add user info to the payload if the model is a pipeline
  545. if "pipeline" in model and model.get("pipeline"):
  546. payload["user"] = {
  547. "name": user.name,
  548. "id": user.id,
  549. "email": user.email,
  550. "role": user.role,
  551. }
  552. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  553. key = request.app.state.config.OPENAI_API_KEYS[idx]
  554. # Fix: o1,o3 does not support the "max_tokens" parameter, Modify "max_tokens" to "max_completion_tokens"
  555. is_o1_o3 = payload["model"].lower().startswith(("o1", "o3-"))
  556. if is_o1_o3:
  557. payload = openai_o1_o3_handler(payload)
  558. elif "api.openai.com" not in url:
  559. # Remove "max_completion_tokens" from the payload for backward compatibility
  560. if "max_completion_tokens" in payload:
  561. payload["max_tokens"] = payload["max_completion_tokens"]
  562. del payload["max_completion_tokens"]
  563. if "max_tokens" in payload and "max_completion_tokens" in payload:
  564. del payload["max_tokens"]
  565. # Convert the modified body back to JSON
  566. payload = json.dumps(payload)
  567. r = None
  568. session = None
  569. streaming = False
  570. response = None
  571. try:
  572. session = aiohttp.ClientSession(
  573. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  574. )
  575. r = await session.request(
  576. method="POST",
  577. url=f"{url}/chat/completions",
  578. data=payload,
  579. headers={
  580. "Authorization": f"Bearer {key}",
  581. "Content-Type": "application/json",
  582. **(
  583. {
  584. "HTTP-Referer": "https://openwebui.com/",
  585. "X-Title": "Open WebUI",
  586. }
  587. if "openrouter.ai" in url
  588. else {}
  589. ),
  590. **(
  591. {
  592. "X-OpenWebUI-User-Name": user.name,
  593. "X-OpenWebUI-User-Id": user.id,
  594. "X-OpenWebUI-User-Email": user.email,
  595. "X-OpenWebUI-User-Role": user.role,
  596. }
  597. if ENABLE_FORWARD_USER_INFO_HEADERS
  598. else {}
  599. ),
  600. },
  601. )
  602. # Check if response is SSE
  603. if "text/event-stream" in r.headers.get("Content-Type", ""):
  604. streaming = True
  605. return StreamingResponse(
  606. r.content,
  607. status_code=r.status,
  608. headers=dict(r.headers),
  609. background=BackgroundTask(
  610. cleanup_response, response=r, session=session
  611. ),
  612. )
  613. else:
  614. try:
  615. response = await r.json()
  616. except Exception as e:
  617. log.error(e)
  618. response = await r.text()
  619. r.raise_for_status()
  620. return response
  621. except Exception as e:
  622. log.exception(e)
  623. detail = None
  624. if isinstance(response, dict):
  625. if "error" in response:
  626. detail = f"{response['error']['message'] if 'message' in response['error'] else response['error']}"
  627. elif isinstance(response, str):
  628. detail = response
  629. raise HTTPException(
  630. status_code=r.status if r else 500,
  631. detail=detail if detail else "Open WebUI: Server Connection Error",
  632. )
  633. finally:
  634. if not streaming and session:
  635. if r:
  636. r.close()
  637. await session.close()
  638. @router.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  639. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  640. """
  641. Deprecated: proxy all requests to OpenAI API
  642. """
  643. body = await request.body()
  644. idx = 0
  645. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  646. key = request.app.state.config.OPENAI_API_KEYS[idx]
  647. r = None
  648. session = None
  649. streaming = False
  650. try:
  651. session = aiohttp.ClientSession(trust_env=True)
  652. r = await session.request(
  653. method=request.method,
  654. url=f"{url}/{path}",
  655. data=body,
  656. headers={
  657. "Authorization": f"Bearer {key}",
  658. "Content-Type": "application/json",
  659. **(
  660. {
  661. "X-OpenWebUI-User-Name": user.name,
  662. "X-OpenWebUI-User-Id": user.id,
  663. "X-OpenWebUI-User-Email": user.email,
  664. "X-OpenWebUI-User-Role": user.role,
  665. }
  666. if ENABLE_FORWARD_USER_INFO_HEADERS
  667. else {}
  668. ),
  669. },
  670. )
  671. r.raise_for_status()
  672. # Check if response is SSE
  673. if "text/event-stream" in r.headers.get("Content-Type", ""):
  674. streaming = True
  675. return StreamingResponse(
  676. r.content,
  677. status_code=r.status,
  678. headers=dict(r.headers),
  679. background=BackgroundTask(
  680. cleanup_response, response=r, session=session
  681. ),
  682. )
  683. else:
  684. response_data = await r.json()
  685. return response_data
  686. except Exception as e:
  687. log.exception(e)
  688. detail = None
  689. if r is not None:
  690. try:
  691. res = await r.json()
  692. log.error(res)
  693. if "error" in res:
  694. detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  695. except Exception:
  696. detail = f"External: {e}"
  697. raise HTTPException(
  698. status_code=r.status if r else 500,
  699. detail=detail if detail else "Open WebUI: Server Connection Error",
  700. )
  701. finally:
  702. if not streaming and session:
  703. if r:
  704. r.close()
  705. await session.close()