openai.py 28 KB

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