openai.py 31 KB

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