openai.py 29 KB

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