openai.py 36 KB

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