openai.py 37 KB

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