openai.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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. prefix_id = api_config.get("prefix_id", None)
  298. tags = api_config.get("tags", [])
  299. if prefix_id:
  300. for model in (
  301. response if isinstance(response, list) else response.get("data", [])
  302. ):
  303. model["id"] = f"{prefix_id}.{model['id']}"
  304. if tags:
  305. for model in (
  306. response if isinstance(response, list) else response.get("data", [])
  307. ):
  308. model["tags"] = tags
  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. "urlIdx": idx,
  347. }
  348. for model in models
  349. if (model.get("id") or model.get("name"))
  350. and (
  351. "api.openai.com"
  352. not in request.app.state.config.OPENAI_API_BASE_URLS[idx]
  353. or not any(
  354. name in model["id"]
  355. for name in [
  356. "babbage",
  357. "dall-e",
  358. "davinci",
  359. "embedding",
  360. "tts",
  361. "whisper",
  362. ]
  363. )
  364. )
  365. ]
  366. )
  367. return merged_list
  368. models = {"data": merge_models_lists(map(extract_data, responses))}
  369. log.debug(f"models: {models}")
  370. request.app.state.OPENAI_MODELS = {model["id"]: model for model in models["data"]}
  371. return models
  372. @router.get("/models")
  373. @router.get("/models/{url_idx}")
  374. async def get_models(
  375. request: Request, url_idx: Optional[int] = None, user=Depends(get_verified_user)
  376. ):
  377. models = {
  378. "data": [],
  379. }
  380. if url_idx is None:
  381. models = await get_all_models(request, user=user)
  382. else:
  383. url = request.app.state.config.OPENAI_API_BASE_URLS[url_idx]
  384. key = request.app.state.config.OPENAI_API_KEYS[url_idx]
  385. r = None
  386. async with aiohttp.ClientSession(
  387. timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
  388. ) as session:
  389. try:
  390. async with session.get(
  391. f"{url}/models",
  392. headers={
  393. "Authorization": f"Bearer {key}",
  394. "Content-Type": "application/json",
  395. **(
  396. {
  397. "X-OpenWebUI-User-Name": user.name,
  398. "X-OpenWebUI-User-Id": user.id,
  399. "X-OpenWebUI-User-Email": user.email,
  400. "X-OpenWebUI-User-Role": user.role,
  401. }
  402. if ENABLE_FORWARD_USER_INFO_HEADERS
  403. else {}
  404. ),
  405. },
  406. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  407. ) as r:
  408. if r.status != 200:
  409. # Extract response error details if available
  410. error_detail = f"HTTP Error: {r.status}"
  411. res = await r.json()
  412. if "error" in res:
  413. error_detail = f"External Error: {res['error']}"
  414. raise Exception(error_detail)
  415. response_data = await r.json()
  416. # Check if we're calling OpenAI API based on the URL
  417. if "api.openai.com" in url:
  418. # Filter models according to the specified conditions
  419. response_data["data"] = [
  420. model
  421. for model in response_data.get("data", [])
  422. if not any(
  423. name in model["id"]
  424. for name in [
  425. "babbage",
  426. "dall-e",
  427. "davinci",
  428. "embedding",
  429. "tts",
  430. "whisper",
  431. ]
  432. )
  433. ]
  434. models = response_data
  435. except aiohttp.ClientError as e:
  436. # ClientError covers all aiohttp requests issues
  437. log.exception(f"Client error: {str(e)}")
  438. raise HTTPException(
  439. status_code=500, detail="Open WebUI: Server Connection Error"
  440. )
  441. except Exception as e:
  442. log.exception(f"Unexpected error: {e}")
  443. error_detail = f"Unexpected error: {str(e)}"
  444. raise HTTPException(status_code=500, detail=error_detail)
  445. if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
  446. models["data"] = await get_filtered_models(models, user)
  447. return models
  448. class ConnectionVerificationForm(BaseModel):
  449. url: str
  450. key: str
  451. @router.post("/verify")
  452. async def verify_connection(
  453. form_data: ConnectionVerificationForm, user=Depends(get_admin_user)
  454. ):
  455. url = form_data.url
  456. key = form_data.key
  457. async with aiohttp.ClientSession(
  458. timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
  459. ) as session:
  460. try:
  461. async with session.get(
  462. f"{url}/models",
  463. headers={
  464. "Authorization": f"Bearer {key}",
  465. "Content-Type": "application/json",
  466. **(
  467. {
  468. "X-OpenWebUI-User-Name": user.name,
  469. "X-OpenWebUI-User-Id": user.id,
  470. "X-OpenWebUI-User-Email": user.email,
  471. "X-OpenWebUI-User-Role": user.role,
  472. }
  473. if ENABLE_FORWARD_USER_INFO_HEADERS
  474. else {}
  475. ),
  476. },
  477. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  478. ) as r:
  479. if r.status != 200:
  480. # Extract response error details if available
  481. error_detail = f"HTTP Error: {r.status}"
  482. res = await r.json()
  483. if "error" in res:
  484. error_detail = f"External Error: {res['error']}"
  485. raise Exception(error_detail)
  486. response_data = await r.json()
  487. return response_data
  488. except aiohttp.ClientError as e:
  489. # ClientError covers all aiohttp requests issues
  490. log.exception(f"Client error: {str(e)}")
  491. raise HTTPException(
  492. status_code=500, detail="Open WebUI: Server Connection Error"
  493. )
  494. except Exception as e:
  495. log.exception(f"Unexpected error: {e}")
  496. error_detail = f"Unexpected error: {str(e)}"
  497. raise HTTPException(status_code=500, detail=error_detail)
  498. @router.post("/chat/completions")
  499. async def generate_chat_completion(
  500. request: Request,
  501. form_data: dict,
  502. user=Depends(get_verified_user),
  503. bypass_filter: Optional[bool] = False,
  504. ):
  505. if BYPASS_MODEL_ACCESS_CONTROL:
  506. bypass_filter = True
  507. idx = 0
  508. payload = {**form_data}
  509. metadata = payload.pop("metadata", None)
  510. model_id = form_data.get("model")
  511. model_info = Models.get_model_by_id(model_id)
  512. # Check model info and override the payload
  513. if model_info:
  514. if model_info.base_model_id:
  515. payload["model"] = model_info.base_model_id
  516. model_id = model_info.base_model_id
  517. params = model_info.params.model_dump()
  518. payload = apply_model_params_to_body_openai(params, payload)
  519. payload = apply_model_system_prompt_to_body(params, payload, metadata, user)
  520. # Check if user has access to the model
  521. if not bypass_filter and user.role == "user":
  522. if not (
  523. user.id == model_info.user_id
  524. or has_access(
  525. user.id, type="read", access_control=model_info.access_control
  526. )
  527. ):
  528. raise HTTPException(
  529. status_code=403,
  530. detail="Model not found",
  531. )
  532. elif not bypass_filter:
  533. if user.role != "admin":
  534. raise HTTPException(
  535. status_code=403,
  536. detail="Model not found",
  537. )
  538. await get_all_models(request, user=user)
  539. model = request.app.state.OPENAI_MODELS.get(model_id)
  540. if model:
  541. idx = model["urlIdx"]
  542. else:
  543. raise HTTPException(
  544. status_code=404,
  545. detail="Model not found",
  546. )
  547. # Get the API config for the model
  548. api_config = request.app.state.config.OPENAI_API_CONFIGS.get(
  549. str(idx),
  550. request.app.state.config.OPENAI_API_CONFIGS.get(
  551. request.app.state.config.OPENAI_API_BASE_URLS[idx], {}
  552. ), # Legacy support
  553. )
  554. prefix_id = api_config.get("prefix_id", None)
  555. if prefix_id:
  556. payload["model"] = payload["model"].replace(f"{prefix_id}.", "")
  557. # Add user info to the payload if the model is a pipeline
  558. if "pipeline" in model and model.get("pipeline"):
  559. payload["user"] = {
  560. "name": user.name,
  561. "id": user.id,
  562. "email": user.email,
  563. "role": user.role,
  564. }
  565. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  566. key = request.app.state.config.OPENAI_API_KEYS[idx]
  567. # Check if model is from "o" series
  568. is_o_series = payload["model"].lower().startswith(("o1", "o3", "o4"))
  569. if is_o_series:
  570. payload = openai_o_series_handler(payload)
  571. elif "api.openai.com" not in url:
  572. # Remove "max_completion_tokens" from the payload for backward compatibility
  573. if "max_completion_tokens" in payload:
  574. payload["max_tokens"] = payload["max_completion_tokens"]
  575. del payload["max_completion_tokens"]
  576. if "max_tokens" in payload and "max_completion_tokens" in payload:
  577. del payload["max_tokens"]
  578. # Convert the modified body back to JSON
  579. if "logit_bias" in payload:
  580. payload["logit_bias"] = json.loads(
  581. convert_logit_bias_input_to_json(payload["logit_bias"])
  582. )
  583. payload = json.dumps(payload)
  584. r = None
  585. session = None
  586. streaming = False
  587. response = None
  588. try:
  589. session = aiohttp.ClientSession(
  590. trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
  591. )
  592. r = await session.request(
  593. method="POST",
  594. url=f"{url}/chat/completions",
  595. data=payload,
  596. headers={
  597. "Authorization": f"Bearer {key}",
  598. "Content-Type": "application/json",
  599. **(
  600. {
  601. "HTTP-Referer": "https://openwebui.com/",
  602. "X-Title": "Open WebUI",
  603. }
  604. if "openrouter.ai" in url
  605. else {}
  606. ),
  607. **(
  608. {
  609. "X-OpenWebUI-User-Name": user.name,
  610. "X-OpenWebUI-User-Id": user.id,
  611. "X-OpenWebUI-User-Email": user.email,
  612. "X-OpenWebUI-User-Role": user.role,
  613. }
  614. if ENABLE_FORWARD_USER_INFO_HEADERS
  615. else {}
  616. ),
  617. },
  618. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  619. )
  620. # Check if response is SSE
  621. if "text/event-stream" in r.headers.get("Content-Type", ""):
  622. streaming = True
  623. return StreamingResponse(
  624. r.content,
  625. status_code=r.status,
  626. headers=dict(r.headers),
  627. background=BackgroundTask(
  628. cleanup_response, response=r, session=session
  629. ),
  630. )
  631. else:
  632. try:
  633. response = await r.json()
  634. except Exception as e:
  635. log.error(e)
  636. response = await r.text()
  637. r.raise_for_status()
  638. return response
  639. except Exception as e:
  640. log.exception(e)
  641. detail = None
  642. if isinstance(response, dict):
  643. if "error" in response:
  644. detail = f"{response['error']['message'] if 'message' in response['error'] else response['error']}"
  645. elif isinstance(response, str):
  646. detail = response
  647. raise HTTPException(
  648. status_code=r.status if r else 500,
  649. detail=detail if detail else "Open WebUI: Server Connection Error",
  650. )
  651. finally:
  652. if not streaming and session:
  653. if r:
  654. r.close()
  655. await session.close()
  656. @router.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  657. async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
  658. """
  659. Deprecated: proxy all requests to OpenAI API
  660. """
  661. body = await request.body()
  662. idx = 0
  663. url = request.app.state.config.OPENAI_API_BASE_URLS[idx]
  664. key = request.app.state.config.OPENAI_API_KEYS[idx]
  665. r = None
  666. session = None
  667. streaming = False
  668. try:
  669. session = aiohttp.ClientSession(trust_env=True)
  670. r = await session.request(
  671. method=request.method,
  672. url=f"{url}/{path}",
  673. data=body,
  674. headers={
  675. "Authorization": f"Bearer {key}",
  676. "Content-Type": "application/json",
  677. **(
  678. {
  679. "X-OpenWebUI-User-Name": user.name,
  680. "X-OpenWebUI-User-Id": user.id,
  681. "X-OpenWebUI-User-Email": user.email,
  682. "X-OpenWebUI-User-Role": user.role,
  683. }
  684. if ENABLE_FORWARD_USER_INFO_HEADERS
  685. else {}
  686. ),
  687. },
  688. ssl=AIOHTTP_CLIENT_SESSION_SSL,
  689. )
  690. r.raise_for_status()
  691. # Check if response is SSE
  692. if "text/event-stream" in r.headers.get("Content-Type", ""):
  693. streaming = True
  694. return StreamingResponse(
  695. r.content,
  696. status_code=r.status,
  697. headers=dict(r.headers),
  698. background=BackgroundTask(
  699. cleanup_response, response=r, session=session
  700. ),
  701. )
  702. else:
  703. response_data = await r.json()
  704. return response_data
  705. except Exception as e:
  706. log.exception(e)
  707. detail = None
  708. if r is not None:
  709. try:
  710. res = await r.json()
  711. log.error(res)
  712. if "error" in res:
  713. detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
  714. except Exception:
  715. detail = f"External: {e}"
  716. raise HTTPException(
  717. status_code=r.status if r else 500,
  718. detail=detail if detail else "Open WebUI: Server Connection Error",
  719. )
  720. finally:
  721. if not streaming and session:
  722. if r:
  723. r.close()
  724. await session.close()