openai.py 34 KB

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