openai.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. import asyncio
  2. import hashlib
  3. import json
  4. import logging
  5. from typing import Optional
  6. import aiohttp
  7. from aiocache import cached
  8. import requests
  9. from urllib.parse import quote
  10. from azure.identity import DefaultAzureCredential, get_bearer_token_provider
  11. from fastapi import Depends, HTTPException, Request, APIRouter
  12. from fastapi.responses import (
  13. FileResponse,
  14. StreamingResponse,
  15. JSONResponse,
  16. PlainTextResponse,
  17. )
  18. from pydantic import BaseModel
  19. from starlette.background import BackgroundTask
  20. from open_webui.models.models import Models
  21. from open_webui.config import (
  22. CACHE_DIR,
  23. )
  24. from open_webui.env import (
  25. MODELS_CACHE_TTL,
  26. AIOHTTP_CLIENT_SESSION_SSL,
  27. AIOHTTP_CLIENT_TIMEOUT,
  28. AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST,
  29. ENABLE_FORWARD_USER_INFO_HEADERS,
  30. BYPASS_MODEL_ACCESS_CONTROL,
  31. )
  32. from open_webui.models.users import UserModel
  33. from open_webui.constants import ERROR_MESSAGES
  34. from open_webui.env import SRC_LOG_LEVELS
  35. from open_webui.utils.payload import (
  36. apply_model_params_to_body_openai,
  37. apply_system_prompt_to_body,
  38. )
  39. from open_webui.utils.misc import (
  40. convert_logit_bias_input_to_json,
  41. )
  42. from open_webui.utils.auth import get_admin_user, get_verified_user
  43. from open_webui.utils.access_control import has_access
  44. log = logging.getLogger(__name__)
  45. log.setLevel(SRC_LOG_LEVELS["OPENAI"])
  46. ##########################################
  47. #
  48. # Utility functions
  49. #
  50. ##########################################
  51. async def send_get_request(url, key=None, user: UserModel = None):
  52. timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
  53. try:
  54. async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
  55. async with session.get(
  56. url,
  57. headers={
  58. **({"Authorization": f"Bearer {key}"} if key else {}),
  59. **(
  60. {
  61. "X-OpenWebUI-User-Name": quote(user.name, safe=" "),
  62. "X-OpenWebUI-User-Id": user.id,
  63. "X-OpenWebUI-User-Email": user.email,
  64. "X-OpenWebUI-User-Role": user.role,
  65. }
  66. if ENABLE_FORWARD_USER_INFO_HEADERS and user
  67. else {}
  68. ),
  69. },
  70. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  71. ) as response:
  72. return await response.json()
  73. except Exception as e:
  74. # Handle connection error here
  75. log.error(f"Connection error: {e}")
  76. return None
  77. async def cleanup_response(
  78. response: Optional[aiohttp.ClientResponse],
  79. session: Optional[aiohttp.ClientSession],
  80. ):
  81. if response:
  82. response.close()
  83. if session:
  84. await session.close()
  85. def openai_reasoning_model_handler(payload):
  86. """
  87. Handle reasoning model specific parameters
  88. """
  89. if "max_tokens" in payload:
  90. # Convert "max_tokens" to "max_completion_tokens" for all reasoning models
  91. payload["max_completion_tokens"] = payload["max_tokens"]
  92. del payload["max_tokens"]
  93. # Handle system role conversion based on model type
  94. if payload["messages"][0]["role"] == "system":
  95. model_lower = payload["model"].lower()
  96. # Legacy models use "user" role instead of "system"
  97. if model_lower.startswith("o1-mini") or model_lower.startswith("o1-preview"):
  98. payload["messages"][0]["role"] = "user"
  99. else:
  100. payload["messages"][0]["role"] = "developer"
  101. return payload
  102. def get_headers_and_cookies(
  103. request: Request,
  104. url,
  105. key=None,
  106. config=None,
  107. metadata: Optional[dict] = None,
  108. user: UserModel = None,
  109. ):
  110. cookies = {}
  111. headers = {
  112. "Content-Type": "application/json",
  113. **(
  114. {
  115. "HTTP-Referer": "https://openwebui.com/",
  116. "X-Title": "Open WebUI",
  117. }
  118. if "openrouter.ai" in url
  119. else {}
  120. ),
  121. **(
  122. {
  123. "X-OpenWebUI-User-Name": quote(user.name, safe=" "),
  124. "X-OpenWebUI-User-Id": user.id,
  125. "X-OpenWebUI-User-Email": user.email,
  126. "X-OpenWebUI-User-Role": user.role,
  127. **(
  128. {"X-OpenWebUI-Chat-Id": metadata.get("chat_id")}
  129. if metadata and metadata.get("chat_id")
  130. else {}
  131. ),
  132. }
  133. if ENABLE_FORWARD_USER_INFO_HEADERS
  134. else {}
  135. ),
  136. }
  137. token = None
  138. auth_type = config.get("auth_type")
  139. if auth_type == "bearer" or auth_type is None:
  140. # Default to bearer if not specified
  141. token = f"{key}"
  142. elif auth_type == "none":
  143. token = None
  144. elif auth_type == "session":
  145. cookies = request.cookies
  146. token = request.state.token.credentials
  147. elif auth_type == "system_oauth":
  148. cookies = request.cookies
  149. oauth_token = None
  150. try:
  151. if request.cookies.get("oauth_session_id", None):
  152. oauth_token = request.app.state.oauth_manager.get_oauth_token(
  153. user.id,
  154. request.cookies.get("oauth_session_id", None),
  155. )
  156. except Exception as e:
  157. log.error(f"Error getting OAuth token: {e}")
  158. if oauth_token:
  159. token = f"{oauth_token.get('access_token', '')}"
  160. elif auth_type in ("azure_ad", "azure_entra_id"):
  161. token = get_azure_entra_id_access_token()
  162. if token:
  163. headers["Authorization"] = f"Bearer {token}"
  164. return headers, cookies
  165. def get_azure_entra_id_access_token():
  166. """
  167. Get Azure access token using DefaultAzureCredential for Azure OpenAI.
  168. Returns the token string or None if authentication fails.
  169. """
  170. try:
  171. token_provider = get_bearer_token_provider(
  172. DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
  173. )
  174. return token_provider()
  175. except Exception as e:
  176. log.error(f"Error getting Azure access token: {e}")
  177. return None
  178. ##########################################
  179. #
  180. # API routes
  181. #
  182. ##########################################
  183. router = APIRouter()
  184. @router.get("/config")
  185. async def get_config(request: Request, user=Depends(get_admin_user)):
  186. return {
  187. "ENABLE_OPENAI_API": request.app.state.config.ENABLE_OPENAI_API,
  188. "OPENAI_API_BASE_URLS": request.app.state.config.OPENAI_API_BASE_URLS,
  189. "OPENAI_API_KEYS": request.app.state.config.OPENAI_API_KEYS,
  190. "OPENAI_API_CONFIGS": request.app.state.config.OPENAI_API_CONFIGS,
  191. }
  192. class OpenAIConfigForm(BaseModel):
  193. ENABLE_OPENAI_API: Optional[bool] = None
  194. OPENAI_API_BASE_URLS: list[str]
  195. OPENAI_API_KEYS: list[str]
  196. OPENAI_API_CONFIGS: dict
  197. @router.post("/config/update")
  198. async def update_config(
  199. request: Request, form_data: OpenAIConfigForm, user=Depends(get_admin_user)
  200. ):
  201. request.app.state.config.ENABLE_OPENAI_API = form_data.ENABLE_OPENAI_API
  202. request.app.state.config.OPENAI_API_BASE_URLS = form_data.OPENAI_API_BASE_URLS
  203. request.app.state.config.OPENAI_API_KEYS = form_data.OPENAI_API_KEYS
  204. # Check if API KEYS length is same than API URLS length
  205. if len(request.app.state.config.OPENAI_API_KEYS) != len(
  206. request.app.state.config.OPENAI_API_BASE_URLS
  207. ):
  208. if len(request.app.state.config.OPENAI_API_KEYS) > len(
  209. request.app.state.config.OPENAI_API_BASE_URLS
  210. ):
  211. request.app.state.config.OPENAI_API_KEYS = (
  212. request.app.state.config.OPENAI_API_KEYS[
  213. : len(request.app.state.config.OPENAI_API_BASE_URLS)
  214. ]
  215. )
  216. else:
  217. request.app.state.config.OPENAI_API_KEYS += [""] * (
  218. len(request.app.state.config.OPENAI_API_BASE_URLS)
  219. - len(request.app.state.config.OPENAI_API_KEYS)
  220. )
  221. request.app.state.config.OPENAI_API_CONFIGS = form_data.OPENAI_API_CONFIGS
  222. # Remove the API configs that are not in the API URLS
  223. keys = list(map(str, range(len(request.app.state.config.OPENAI_API_BASE_URLS))))
  224. request.app.state.config.OPENAI_API_CONFIGS = {
  225. key: value
  226. for key, value in request.app.state.config.OPENAI_API_CONFIGS.items()
  227. if key in keys
  228. }
  229. return {
  230. "ENABLE_OPENAI_API": request.app.state.config.ENABLE_OPENAI_API,
  231. "OPENAI_API_BASE_URLS": request.app.state.config.OPENAI_API_BASE_URLS,
  232. "OPENAI_API_KEYS": request.app.state.config.OPENAI_API_KEYS,
  233. "OPENAI_API_CONFIGS": request.app.state.config.OPENAI_API_CONFIGS,
  234. }
  235. @router.post("/audio/speech")
  236. async def speech(request: Request, user=Depends(get_verified_user)):
  237. idx = None
  238. try:
  239. idx = request.app.state.config.OPENAI_API_BASE_URLS.index(
  240. "https://api.openai.com/v1"
  241. )
  242. body = await request.body()
  243. name = hashlib.sha256(body).hexdigest()
  244. SPEECH_CACHE_DIR = CACHE_DIR / "audio" / "speech"
  245. SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
  246. file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
  247. file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
  248. # Check if the file already exists in the cache
  249. if file_path.is_file():
  250. return FileResponse(file_path)
  251. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  252. key = request.app.state.config.OPENAI_API_KEYS[idx]
  253. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  254. str(idx),
  255. request.app.state.config.OPENAI_API_CONFIGS.get(url, {}), # Legacy support
  256. )
  257. headers, cookies = get_headers_and_cookies(
  258. request, url, key, api_config, user=user
  259. )
  260. r = None
  261. try:
  262. r = requests.post(
  263. url=f"{url}/audio/speech",
  264. data=body,
  265. headers=headers,
  266. cookies=cookies,
  267. stream=True,
  268. )
  269. r.raise_for_status()
  270. # Save the streaming content to a file
  271. with open(file_path, "wb") as f:
  272. for chunk in r.iter_content(chunk_size=8192):
  273. f.write(chunk)
  274. with open(file_body_path, "w") as f:
  275. json.dump(json.loads(body.decode("utf-8")), f)
  276. # Return the saved file
  277. return FileResponse(file_path)
  278. except Exception as e:
  279. log.exception(e)
  280. detail = None
  281. if r is not None:
  282. try:
  283. res = r.json()
  284. if "error" in res:
  285. detail = f"External: {res['error']}"
  286. except Exception:
  287. detail = f"External: {e}"
  288. raise HTTPException(
  289. status_code=r.status_code if r else 500,
  290. detail=detail if detail else "Open WebUI: Server Connection Error",
  291. )
  292. except ValueError:
  293. raise HTTPException(status_code=401, detail=ERROR_MESSAGES.OPENAI_NOT_FOUND)
  294. async def get_all_models_responses(request: Request, user: UserModel) -> list:
  295. if not request.app.state.config.ENABLE_OPENAI_API:
  296. return []
  297. # Check if API KEYS length is same than API URLS length
  298. num_urls = len(request.app.state.config.OPENAI_API_BASE_URLS)
  299. num_keys = len(request.app.state.config.OPENAI_API_KEYS)
  300. if num_keys != num_urls:
  301. # if there are more keys than urls, remove the extra keys
  302. if num_keys > num_urls:
  303. new_keys = request.app.state.config.OPENAI_API_KEYS[:num_urls]
  304. request.app.state.config.OPENAI_API_KEYS = new_keys
  305. # if there are more urls than keys, add empty keys
  306. else:
  307. request.app.state.config.OPENAI_API_KEYS += [""] * (num_urls - num_keys)
  308. request_tasks = []
  309. for idx, url in enumerate(request.app.state.config.OPENAI_API_BASE_URLS):
  310. if (str(idx) not in request.app.state.config.OPENAI_API_CONFIGS) and (
  311. url not in request.app.state.config.OPENAI_API_CONFIGS # Legacy support
  312. ):
  313. request_tasks.append(
  314. send_get_request(
  315. f"{url}/models",
  316. request.app.state.config.OPENAI_API_KEYS[idx],
  317. user=user,
  318. )
  319. )
  320. else:
  321. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  322. str(idx),
  323. request.app.state.config.OPENAI_API_CONFIGS.get(
  324. url, {}
  325. ), # Legacy support
  326. )
  327. enable = api_config.get("enable", True)
  328. model_ids = api_config.get("model_ids", [])
  329. if enable:
  330. if len(model_ids) == 0:
  331. request_tasks.append(
  332. send_get_request(
  333. f"{url}/models",
  334. request.app.state.config.OPENAI_API_KEYS[idx],
  335. user=user,
  336. )
  337. )
  338. else:
  339. model_list = {
  340. "object": "list",
  341. "data": [
  342. {
  343. "id": model_id,
  344. "name": model_id,
  345. "owned_by": "openai",
  346. "openai": {"id": model_id},
  347. "urlIdx": idx,
  348. }
  349. for model_id in model_ids
  350. ],
  351. }
  352. request_tasks.append(
  353. asyncio.ensure_future(asyncio.sleep(0, model_list))
  354. )
  355. else:
  356. request_tasks.append(asyncio.ensure_future(asyncio.sleep(0, None)))
  357. responses = await asyncio.gather(*request_tasks)
  358. for idx, response in enumerate(responses):
  359. if response:
  360. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  361. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  362. str(idx),
  363. request.app.state.config.OPENAI_API_CONFIGS.get(
  364. url, {}
  365. ), # Legacy support
  366. )
  367. connection_type = api_config.get("connection_type", "external")
  368. prefix_id = api_config.get("prefix_id", None)
  369. tags = api_config.get("tags", [])
  370. model_list = (
  371. response if isinstance(response, list) else response.get("data", [])
  372. )
  373. if not isinstance(model_list, list):
  374. # Catch non-list responses
  375. model_list = []
  376. for model in model_list:
  377. # Remove name key if its value is None #16689
  378. if "name" in model and model["name"] is None:
  379. del model["name"]
  380. if prefix_id:
  381. model["id"] = (
  382. f"{prefix_id}.{model.get('id', model.get('name', ''))}"
  383. )
  384. if tags:
  385. model["tags"] = tags
  386. if connection_type:
  387. model["connection_type"] = connection_type
  388. log.debug(f"get_all_models:responses() {responses}")
  389. return responses
  390. async def get_filtered_models(models, user):
  391. # Filter models based on user access control
  392. filtered_models = []
  393. for model in models.get("data", []):
  394. model_info = Models.get_model_by_id(model["id"])
  395. if model_info:
  396. if user.id == model_info.user_id or has_access(
  397. user.id, type="read", access_control=model_info.access_control
  398. ):
  399. filtered_models.append(model)
  400. return filtered_models
  401. @cached(
  402. ttl=MODELS_CACHE_TTL,
  403. key=lambda _, user: f"openai_all_models_{user.id}" if user else "openai_all_models",
  404. )
  405. async def get_all_models(request: Request, user: UserModel) -> dict[str, list]:
  406. log.info("get_all_models()")
  407. if not request.app.state.config.ENABLE_OPENAI_API:
  408. return {"data": []}
  409. responses = await get_all_models_responses(request, user=user)
  410. def extract_data(response):
  411. if response and "data" in response:
  412. return response["data"]
  413. if isinstance(response, list):
  414. return response
  415. return None
  416. def merge_models_lists(model_lists):
  417. log.debug(f"merge_models_lists {model_lists}")
  418. merged_list = []
  419. for idx, models in enumerate(model_lists):
  420. if models is not None and "error" not in models:
  421. merged_list.extend(
  422. [
  423. {
  424. **model,
  425. "name": model.get("name", model["id"]),
  426. "owned_by": "openai",
  427. "openai": model,
  428. "connection_type": model.get("connection_type", "external"),
  429. "urlIdx": idx,
  430. }
  431. for model in models
  432. if (model.get("id") or model.get("name"))
  433. and (
  434. "api.openai.com"
  435. not in request.app.state.config.OPENAI_API_BASE_URLS[idx]
  436. or not any(
  437. name in model["id"]
  438. for name in [
  439. "babbage",
  440. "dall-e",
  441. "davinci",
  442. "embedding",
  443. "tts",
  444. "whisper",
  445. ]
  446. )
  447. )
  448. ]
  449. )
  450. return merged_list
  451. models = {"data": merge_models_lists(map(extract_data, responses))}
  452. log.debug(f"models: {models}")
  453. request.app.state.OPENAI_MODELS = {model["id"]: model for model in models["data"]}
  454. return models
  455. @router.get("/models")
  456. @router.get("/models/{url_idx}")
  457. async def get_models(
  458. request: Request, url_idx: Optional[int] = None, user=Depends(get_verified_user)
  459. ):
  460. models = {
  461. "data": [],
  462. }
  463. if url_idx is None:
  464. models = await get_all_models(request, user=user)
  465. else:
  466. url = request.app.state.config.OPENAI_API_BASE_URLS[url_idx]
  467. key = request.app.state.config.OPENAI_API_KEYS[url_idx]
  468. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  469. str(url_idx),
  470. request.app.state.config.OPENAI_API_CONFIGS.get(url, {}), # Legacy support
  471. )
  472. r = None
  473. async with aiohttp.ClientSession(
  474. trust_env=True,
  475. timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST),
  476. ) as session:
  477. try:
  478. headers, cookies = get_headers_and_cookies(
  479. request, url, key, api_config, user=user
  480. )
  481. if api_config.get("azure", False):
  482. models = {
  483. "data": api_config.get("model_ids", []) or [],
  484. "object": "list",
  485. }
  486. else:
  487. async with session.get(
  488. f"{url}/models",
  489. headers=headers,
  490. cookies=cookies,
  491. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  492. ) as r:
  493. if r.status != 200:
  494. # Extract response error details if available
  495. error_detail = f"HTTP Error: {r.status}"
  496. res = await r.json()
  497. if "error" in res:
  498. error_detail = f"External Error: {res['error']}"
  499. raise Exception(error_detail)
  500. response_data = await r.json()
  501. # Check if we're calling OpenAI API based on the URL
  502. if "api.openai.com" in url:
  503. # Filter models according to the specified conditions
  504. response_data["data"] = [
  505. model
  506. for model in response_data.get("data", [])
  507. if not any(
  508. name in model["id"]
  509. for name in [
  510. "babbage",
  511. "dall-e",
  512. "davinci",
  513. "embedding",
  514. "tts",
  515. "whisper",
  516. ]
  517. )
  518. ]
  519. models = response_data
  520. except aiohttp.ClientError as e:
  521. # ClientError covers all aiohttp requests issues
  522. log.exception(f"Client error: {str(e)}")
  523. raise HTTPException(
  524. status_code=500, detail="Open WebUI: Server Connection Error"
  525. )
  526. except Exception as e:
  527. log.exception(f"Unexpected error: {e}")
  528. error_detail = f"Unexpected error: {str(e)}"
  529. raise HTTPException(status_code=500, detail=error_detail)
  530. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  531. models["data"] = await get_filtered_models(models, user)
  532. return models
  533. class ConnectionVerificationForm(BaseModel):
  534. url: str
  535. key: str
  536. config: Optional[dict] = None
  537. @router.post("/verify")
  538. async def verify_connection(
  539. request: Request,
  540. form_data: ConnectionVerificationForm,
  541. user=Depends(get_admin_user),
  542. ):
  543. url = form_data.url
  544. key = form_data.key
  545. api_config = form_data.config or {}
  546. async with aiohttp.ClientSession(
  547. trust_env=True,
  548. timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST),
  549. ) as session:
  550. try:
  551. headers, cookies = get_headers_and_cookies(
  552. request, url, key, api_config, user=user
  553. )
  554. if api_config.get("azure", False):
  555. # Only set api-key header if not using Azure Entra ID authentication
  556. auth_type = api_config.get("auth_type", "bearer")
  557. if auth_type not in ("azure_ad", "azure_entra_id"):
  558. headers["api-key"] = key
  559. api_version = api_config.get("api_version", "") or "2023-03-15-preview"
  560. async with session.get(
  561. url=f"{url}/openai/models?api-version={api_version}",
  562. headers=headers,
  563. cookies=cookies,
  564. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  565. ) as r:
  566. try:
  567. response_data = await r.json()
  568. except Exception:
  569. response_data = await r.text()
  570. if r.status != 200:
  571. if isinstance(response_data, (dict, list)):
  572. return JSONResponse(
  573. status_code=r.status, content=response_data
  574. )
  575. else:
  576. return PlainTextResponse(
  577. status_code=r.status, content=response_data
  578. )
  579. return response_data
  580. else:
  581. async with session.get(
  582. f"{url}/models",
  583. headers=headers,
  584. cookies=cookies,
  585. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  586. ) as r:
  587. try:
  588. response_data = await r.json()
  589. except Exception:
  590. response_data = await r.text()
  591. if r.status != 200:
  592. if isinstance(response_data, (dict, list)):
  593. return JSONResponse(
  594. status_code=r.status, content=response_data
  595. )
  596. else:
  597. return PlainTextResponse(
  598. status_code=r.status, content=response_data
  599. )
  600. return response_data
  601. except aiohttp.ClientError as e:
  602. # ClientError covers all aiohttp requests issues
  603. log.exception(f"Client error: {str(e)}")
  604. raise HTTPException(
  605. status_code=500, detail="Open WebUI: Server Connection Error"
  606. )
  607. except Exception as e:
  608. log.exception(f"Unexpected error: {e}")
  609. raise HTTPException(
  610. status_code=500, detail="Open WebUI: Server Connection Error"
  611. )
  612. def get_azure_allowed_params(api_version: str) -> set[str]:
  613. allowed_params = {
  614. "messages",
  615. "temperature",
  616. "role",
  617. "content",
  618. "contentPart",
  619. "contentPartImage",
  620. "enhancements",
  621. "dataSources",
  622. "n",
  623. "stream",
  624. "stop",
  625. "max_tokens",
  626. "presence_penalty",
  627. "frequency_penalty",
  628. "logit_bias",
  629. "user",
  630. "function_call",
  631. "functions",
  632. "tools",
  633. "tool_choice",
  634. "top_p",
  635. "log_probs",
  636. "top_logprobs",
  637. "response_format",
  638. "seed",
  639. "max_completion_tokens",
  640. }
  641. try:
  642. if api_version >= "2024-09-01-preview":
  643. allowed_params.add("stream_options")
  644. except ValueError:
  645. log.debug(
  646. f"Invalid API version {api_version} for Azure OpenAI. Defaulting to allowed parameters."
  647. )
  648. return allowed_params
  649. def is_openai_reasoning_model(model: str) -> bool:
  650. return model.lower().startswith(("o1", "o3", "o4", "gpt-5"))
  651. def convert_to_azure_payload(url, payload: dict, api_version: str):
  652. model = payload.get("model", "")
  653. # Filter allowed parameters based on Azure OpenAI API
  654. allowed_params = get_azure_allowed_params(api_version)
  655. # Special handling for o-series models
  656. if is_openai_reasoning_model(model):
  657. # Convert max_tokens to max_completion_tokens for o-series models
  658. if "max_tokens" in payload:
  659. payload["max_completion_tokens"] = payload["max_tokens"]
  660. del payload["max_tokens"]
  661. # Remove temperature if not 1 for o-series models
  662. if "temperature" in payload and payload["temperature"] != 1:
  663. log.debug(
  664. f"Removing temperature parameter for o-series model {model} as only default value (1) is supported"
  665. )
  666. del payload["temperature"]
  667. # Filter out unsupported parameters
  668. payload = {k: v for k, v in payload.items() if k in allowed_params}
  669. url = f"{url}/openai/deployments/{model}"
  670. return url, payload
  671. @router.post("/chat/completions")
  672. async def generate_chat_completion(
  673. request: Request,
  674. form_data: dict,
  675. user=Depends(get_verified_user),
  676. bypass_filter: Optional[bool] = False,
  677. ):
  678. if BYPASS_MODEL_ACCESS_CONTROL:
  679. bypass_filter = True
  680. idx = 0
  681. payload = {**form_data}
  682. metadata = payload.pop("metadata", None)
  683. model_id = form_data.get("model")
  684. model_info = Models.get_model_by_id(model_id)
  685. # Check model info and override the payload
  686. if model_info:
  687. if model_info.base_model_id:
  688. payload["model"] = model_info.base_model_id
  689. model_id = model_info.base_model_id
  690. params = model_info.params.model_dump()
  691. if params:
  692. system = params.pop("system", None)
  693. payload = apply_model_params_to_body_openai(params, payload)
  694. payload = apply_system_prompt_to_body(system, payload, metadata, user)
  695. # Check if user has access to the model
  696. if not bypass_filter and user.role == "user":
  697. if not (
  698. user.id == model_info.user_id
  699. or has_access(
  700. user.id, type="read", access_control=model_info.access_control
  701. )
  702. ):
  703. raise HTTPException(
  704. status_code=403,
  705. detail="Model not found",
  706. )
  707. elif not bypass_filter:
  708. if user.role != "admin":
  709. raise HTTPException(
  710. status_code=403,
  711. detail="Model not found",
  712. )
  713. await get_all_models(request, user=user)
  714. model = request.app.state.OPENAI_MODELS.get(model_id)
  715. if model:
  716. idx = model["urlIdx"]
  717. else:
  718. raise HTTPException(
  719. status_code=404,
  720. detail="Model not found",
  721. )
  722. # Get the API config for the model
  723. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  724. str(idx),
  725. request.app.state.config.OPENAI_API_CONFIGS.get(
  726. request.app.state.config.OPENAI_API_BASE_URLS[idx], {}
  727. ), # Legacy support
  728. )
  729. prefix_id = api_config.get("prefix_id", None)
  730. if prefix_id:
  731. payload["model"] = payload["model"].replace(f"{prefix_id}.", "")
  732. # Add user info to the payload if the model is a pipeline
  733. if "pipeline" in model and model.get("pipeline"):
  734. payload["user"] = {
  735. "name": user.name,
  736. "id": user.id,
  737. "email": user.email,
  738. "role": user.role,
  739. }
  740. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  741. key = request.app.state.config.OPENAI_API_KEYS[idx]
  742. # Check if model is a reasoning model that needs special handling
  743. if is_openai_reasoning_model(payload["model"]):
  744. payload = openai_reasoning_model_handler(payload)
  745. elif "api.openai.com" not in url:
  746. # Remove "max_completion_tokens" from the payload for backward compatibility
  747. if "max_completion_tokens" in payload:
  748. payload["max_tokens"] = payload["max_completion_tokens"]
  749. del payload["max_completion_tokens"]
  750. if "max_tokens" in payload and "max_completion_tokens" in payload:
  751. del payload["max_tokens"]
  752. # Convert the modified body back to JSON
  753. if "logit_bias" in payload:
  754. payload["logit_bias"] = json.loads(
  755. convert_logit_bias_input_to_json(payload["logit_bias"])
  756. )
  757. headers, cookies = get_headers_and_cookies(
  758. request, url, key, api_config, metadata, user=user
  759. )
  760. if api_config.get("azure", False):
  761. api_version = api_config.get("api_version", "2023-03-15-preview")
  762. request_url, payload = convert_to_azure_payload(url, payload, api_version)
  763. # Only set api-key header if not using Azure Entra ID authentication
  764. auth_type = api_config.get("auth_type", "bearer")
  765. if auth_type not in ("azure_ad", "azure_entra_id"):
  766. headers["api-key"] = key
  767. headers["api-version"] = api_version
  768. request_url = f"{request_url}/chat/completions?api-version={api_version}"
  769. else:
  770. request_url = f"{url}/chat/completions"
  771. payload = json.dumps(payload)
  772. r = None
  773. session = None
  774. streaming = False
  775. response = None
  776. try:
  777. session = aiohttp.ClientSession(
  778. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  779. )
  780. r = await session.request(
  781. method="POST",
  782. url=request_url,
  783. data=payload,
  784. headers=headers,
  785. cookies=cookies,
  786. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  787. )
  788. # Check if response is SSE
  789. if "text/event-stream" in r.headers.get("Content-Type", ""):
  790. streaming = True
  791. return StreamingResponse(
  792. r.content,
  793. status_code=r.status,
  794. headers=dict(r.headers),
  795. background=BackgroundTask(
  796. cleanup_response, response=r, session=session
  797. ),
  798. )
  799. else:
  800. try:
  801. response = await r.json()
  802. except Exception as e:
  803. log.error(e)
  804. response = await r.text()
  805. if r.status >= 400:
  806. if isinstance(response, (dict, list)):
  807. return JSONResponse(status_code=r.status, content=response)
  808. else:
  809. return PlainTextResponse(status_code=r.status, content=response)
  810. return response
  811. except Exception as e:
  812. log.exception(e)
  813. raise HTTPException(
  814. status_code=r.status if r else 500,
  815. detail="Open WebUI: Server Connection Error",
  816. )
  817. finally:
  818. if not streaming:
  819. await cleanup_response(r, session)
  820. async def embeddings(request: Request, form_data: dict, user):
  821. """
  822. Calls the embeddings endpoint for OpenAI-compatible providers.
  823. Args:
  824. request (Request): The FastAPI request context.
  825. form_data (dict): OpenAI-compatible embeddings payload.
  826. user (UserModel): The authenticated user.
  827. Returns:
  828. dict: OpenAI-compatible embeddings response.
  829. """
  830. idx = 0
  831. # Prepare payload/body
  832. body = json.dumps(form_data)
  833. # Find correct backend url/key based on model
  834. await get_all_models(request, user=user)
  835. model_id = form_data.get("model")
  836. models = request.app.state.OPENAI_MODELS
  837. if model_id in models:
  838. idx = models[model_id]["urlIdx"]
  839. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  840. key = request.app.state.config.OPENAI_API_KEYS[idx]
  841. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  842. str(idx),
  843. request.app.state.config.OPENAI_API_CONFIGS.get(url, {}), # Legacy support
  844. )
  845. r = None
  846. session = None
  847. streaming = False
  848. headers, cookies = get_headers_and_cookies(request, url, key, api_config, user=user)
  849. try:
  850. session = aiohttp.ClientSession(trust_env=True)
  851. r = await session.request(
  852. method="POST",
  853. url=f"{url}/embeddings",
  854. data=body,
  855. headers=headers,
  856. cookies=cookies,
  857. )
  858. if "text/event-stream" in r.headers.get("Content-Type", ""):
  859. streaming = True
  860. return StreamingResponse(
  861. r.content,
  862. status_code=r.status,
  863. headers=dict(r.headers),
  864. background=BackgroundTask(
  865. cleanup_response, response=r, session=session
  866. ),
  867. )
  868. else:
  869. try:
  870. response_data = await r.json()
  871. except Exception:
  872. response_data = await r.text()
  873. if r.status >= 400:
  874. if isinstance(response_data, (dict, list)):
  875. return JSONResponse(status_code=r.status, content=response_data)
  876. else:
  877. return PlainTextResponse(
  878. status_code=r.status, content=response_data
  879. )
  880. return response_data
  881. except Exception as e:
  882. log.exception(e)
  883. raise HTTPException(
  884. status_code=r.status if r else 500,
  885. detail="Open WebUI: Server Connection Error",
  886. )
  887. finally:
  888. if not streaming:
  889. await cleanup_response(r, session)
  890. @router.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  891. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  892. """
  893. Deprecated: proxy all requests to OpenAI API
  894. """
  895. body = await request.body()
  896. idx = 0
  897. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  898. key = request.app.state.config.OPENAI_API_KEYS[idx]
  899. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  900. str(idx),
  901. request.app.state.config.OPENAI_API_CONFIGS.get(
  902. request.app.state.config.OPENAI_API_BASE_URLS[idx], {}
  903. ), # Legacy support
  904. )
  905. r = None
  906. session = None
  907. streaming = False
  908. try:
  909. headers, cookies = get_headers_and_cookies(
  910. request, url, key, api_config, user=user
  911. )
  912. if api_config.get("azure", False):
  913. api_version = api_config.get("api_version", "2023-03-15-preview")
  914. # Only set api-key header if not using Azure Entra ID authentication
  915. auth_type = api_config.get("auth_type", "bearer")
  916. if auth_type not in ("azure_ad", "azure_entra_id"):
  917. headers["api-key"] = key
  918. headers["api-version"] = api_version
  919. payload = json.loads(body)
  920. url, payload = convert_to_azure_payload(url, payload, api_version)
  921. body = json.dumps(payload).encode()
  922. request_url = f"{url}/{path}?api-version={api_version}"
  923. else:
  924. request_url = f"{url}/{path}"
  925. session = aiohttp.ClientSession(trust_env=True)
  926. r = await session.request(
  927. method=request.method,
  928. url=request_url,
  929. data=body,
  930. headers=headers,
  931. cookies=cookies,
  932. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  933. )
  934. # Check if response is SSE
  935. if "text/event-stream" in r.headers.get("Content-Type", ""):
  936. streaming = True
  937. return StreamingResponse(
  938. r.content,
  939. status_code=r.status,
  940. headers=dict(r.headers),
  941. background=BackgroundTask(
  942. cleanup_response, response=r, session=session
  943. ),
  944. )
  945. else:
  946. try:
  947. response_data = await r.json()
  948. except Exception:
  949. response_data = await r.text()
  950. if r.status >= 400:
  951. if isinstance(response_data, (dict, list)):
  952. return JSONResponse(status_code=r.status, content=response_data)
  953. else:
  954. return PlainTextResponse(
  955. status_code=r.status, content=response_data
  956. )
  957. return response_data
  958. except Exception as e:
  959. log.exception(e)
  960. raise HTTPException(
  961. status_code=r.status if r else 500,
  962. detail="Open WebUI: Server Connection Error",
  963. )
  964. finally:
  965. if not streaming:
  966. await cleanup_response(r, session)