1
0

openai.py 38 KB

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