openai.py 28 KB

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