chat.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import time
  2. import logging
  3. import sys
  4. from aiocache import cached
  5. from typing import Any
  6. import random
  7. import json
  8. import inspect
  9. from fastapi import Request
  10. from starlette.responses import Response, StreamingResponse
  11. from open_webui.socket.main import (
  12. get_event_call,
  13. get_event_emitter,
  14. )
  15. from open_webui.functions import generate_function_chat_completion
  16. from open_webui.routers.openai import (
  17. generate_chat_completion as generate_openai_chat_completion,
  18. )
  19. from open_webui.routers.ollama import (
  20. generate_chat_completion as generate_ollama_chat_completion,
  21. )
  22. from open_webui.routers.pipelines import (
  23. process_pipeline_outlet_filter,
  24. )
  25. from open_webui.models.functions import Functions
  26. from open_webui.models.models import Models
  27. from open_webui.utils.plugin import load_function_module_by_id
  28. from open_webui.utils.access_control import has_access
  29. from open_webui.utils.models import get_all_models
  30. from open_webui.utils.payload import convert_payload_openai_to_ollama
  31. from open_webui.utils.response import (
  32. convert_response_ollama_to_openai,
  33. convert_streaming_response_ollama_to_openai,
  34. )
  35. from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL, BYPASS_MODEL_ACCESS_CONTROL
  36. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  37. log = logging.getLogger(__name__)
  38. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  39. async def generate_chat_completion(
  40. request: Request,
  41. form_data: dict,
  42. user: Any,
  43. bypass_filter: bool = False,
  44. ):
  45. if BYPASS_MODEL_ACCESS_CONTROL:
  46. bypass_filter = True
  47. models = request.app.state.MODELS
  48. model_id = form_data["model"]
  49. if model_id not in models:
  50. raise Exception("Model not found")
  51. model = models[model_id]
  52. # Check if user has access to the model
  53. if not bypass_filter and user.role == "user":
  54. if model.get("arena"):
  55. if not has_access(
  56. user.id,
  57. type="read",
  58. access_control=model.get("info", {})
  59. .get("meta", {})
  60. .get("access_control", {}),
  61. ):
  62. raise Exception("Model not found")
  63. else:
  64. model_info = Models.get_model_by_id(model_id)
  65. if not model_info:
  66. raise Exception("Model not found")
  67. elif not (
  68. user.id == model_info.user_id
  69. or has_access(
  70. user.id, type="read", access_control=model_info.access_control
  71. )
  72. ):
  73. raise Exception("Model not found")
  74. if model["owned_by"] == "arena":
  75. model_ids = model.get("info", {}).get("meta", {}).get("model_ids")
  76. filter_mode = model.get("info", {}).get("meta", {}).get("filter_mode")
  77. if model_ids and filter_mode == "exclude":
  78. model_ids = [
  79. model["id"]
  80. for model in await get_all_models(request)
  81. if model.get("owned_by") != "arena" and model["id"] not in model_ids
  82. ]
  83. selected_model_id = None
  84. if isinstance(model_ids, list) and model_ids:
  85. selected_model_id = random.choice(model_ids)
  86. else:
  87. model_ids = [
  88. model["id"]
  89. for model in await get_all_models(request)
  90. if model.get("owned_by") != "arena"
  91. ]
  92. selected_model_id = random.choice(model_ids)
  93. form_data["model"] = selected_model_id
  94. if form_data.get("stream") == True:
  95. async def stream_wrapper(stream):
  96. yield f"data: {json.dumps({'selected_model_id': selected_model_id})}\n\n"
  97. async for chunk in stream:
  98. yield chunk
  99. response = await generate_chat_completion(
  100. form_data, user, bypass_filter=True
  101. )
  102. return StreamingResponse(
  103. stream_wrapper(response.body_iterator), media_type="text/event-stream"
  104. )
  105. else:
  106. return {
  107. **(await generate_chat_completion(form_data, user, bypass_filter=True)),
  108. "selected_model_id": selected_model_id,
  109. }
  110. if model.get("pipe"):
  111. # Below does not require bypass_filter because this is the only route the uses this function and it is already bypassing the filter
  112. return await generate_function_chat_completion(
  113. form_data, user=user, models=models
  114. )
  115. if model["owned_by"] == "ollama":
  116. # Using /ollama/api/chat endpoint
  117. form_data = convert_payload_openai_to_ollama(form_data)
  118. response = await generate_ollama_chat_completion(
  119. request=request, form_data=form_data, user=user, bypass_filter=bypass_filter
  120. )
  121. if form_data.stream:
  122. response.headers["content-type"] = "text/event-stream"
  123. return StreamingResponse(
  124. convert_streaming_response_ollama_to_openai(response),
  125. headers=dict(response.headers),
  126. )
  127. else:
  128. return convert_response_ollama_to_openai(response)
  129. else:
  130. return await generate_openai_chat_completion(
  131. request=request, form_data=form_data, user=user, bypass_filter=bypass_filter
  132. )
  133. async def chat_completed(request: Request, form_data: dict, user: Any):
  134. await get_all_models(request)
  135. models = request.app.state.MODELS
  136. data = form_data
  137. model_id = data["model"]
  138. if model_id not in models:
  139. raise Exception("Model not found")
  140. model = models[model_id]
  141. try:
  142. data = process_pipeline_outlet_filter(request, data, user, models)
  143. except Exception as e:
  144. return Exception(f"Error: {e}")
  145. __event_emitter__ = get_event_emitter(
  146. {
  147. "chat_id": data["chat_id"],
  148. "message_id": data["id"],
  149. "session_id": data["session_id"],
  150. }
  151. )
  152. __event_call__ = get_event_call(
  153. {
  154. "chat_id": data["chat_id"],
  155. "message_id": data["id"],
  156. "session_id": data["session_id"],
  157. }
  158. )
  159. def get_priority(function_id):
  160. function = Functions.get_function_by_id(function_id)
  161. if function is not None and hasattr(function, "valves"):
  162. # TODO: Fix FunctionModel to include vavles
  163. return (function.valves if function.valves else {}).get("priority", 0)
  164. return 0
  165. filter_ids = [function.id for function in Functions.get_global_filter_functions()]
  166. if "info" in model and "meta" in model["info"]:
  167. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  168. filter_ids = list(set(filter_ids))
  169. enabled_filter_ids = [
  170. function.id
  171. for function in Functions.get_functions_by_type("filter", active_only=True)
  172. ]
  173. filter_ids = [
  174. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  175. ]
  176. # Sort filter_ids by priority, using the get_priority function
  177. filter_ids.sort(key=get_priority)
  178. for filter_id in filter_ids:
  179. filter = Functions.get_function_by_id(filter_id)
  180. if not filter:
  181. continue
  182. if filter_id in request.app.state.FUNCTIONS:
  183. function_module = request.app.state.FUNCTIONS[filter_id]
  184. else:
  185. function_module, _, _ = load_function_module_by_id(filter_id)
  186. request.app.state.FUNCTIONS[filter_id] = function_module
  187. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  188. valves = Functions.get_function_valves_by_id(filter_id)
  189. function_module.valves = function_module.Valves(
  190. **(valves if valves else {})
  191. )
  192. if not hasattr(function_module, "outlet"):
  193. continue
  194. try:
  195. outlet = function_module.outlet
  196. # Get the signature of the function
  197. sig = inspect.signature(outlet)
  198. params = {"body": data}
  199. # Extra parameters to be passed to the function
  200. extra_params = {
  201. "__model__": model,
  202. "__id__": filter_id,
  203. "__event_emitter__": __event_emitter__,
  204. "__event_call__": __event_call__,
  205. }
  206. # Add extra params in contained in function signature
  207. for key, value in extra_params.items():
  208. if key in sig.parameters:
  209. params[key] = value
  210. if "__user__" in sig.parameters:
  211. __user__ = {
  212. "id": user.id,
  213. "email": user.email,
  214. "name": user.name,
  215. "role": user.role,
  216. }
  217. try:
  218. if hasattr(function_module, "UserValves"):
  219. __user__["valves"] = function_module.UserValves(
  220. **Functions.get_user_valves_by_id_and_user_id(
  221. filter_id, user.id
  222. )
  223. )
  224. except Exception as e:
  225. print(e)
  226. params = {**params, "__user__": __user__}
  227. if inspect.iscoroutinefunction(outlet):
  228. data = await outlet(**params)
  229. else:
  230. data = outlet(**params)
  231. except Exception as e:
  232. return Exception(f"Error: {e}")
  233. return data
  234. async def chat_action(request: Request, action_id: str, form_data: dict, user: Any):
  235. if "." in action_id:
  236. action_id, sub_action_id = action_id.split(".")
  237. else:
  238. sub_action_id = None
  239. action = Functions.get_function_by_id(action_id)
  240. if not action:
  241. raise Exception(f"Action not found: {action_id}")
  242. await get_all_models(request)
  243. models = request.app.state.MODELS
  244. data = form_data
  245. model_id = data["model"]
  246. if model_id not in models:
  247. raise Exception("Model not found")
  248. model = models[model_id]
  249. __event_emitter__ = get_event_emitter(
  250. {
  251. "chat_id": data["chat_id"],
  252. "message_id": data["id"],
  253. "session_id": data["session_id"],
  254. }
  255. )
  256. __event_call__ = get_event_call(
  257. {
  258. "chat_id": data["chat_id"],
  259. "message_id": data["id"],
  260. "session_id": data["session_id"],
  261. }
  262. )
  263. if action_id in request.app.state.FUNCTIONS:
  264. function_module = request.app.state.FUNCTIONS[action_id]
  265. else:
  266. function_module, _, _ = load_function_module_by_id(action_id)
  267. request.app.state.FUNCTIONS[action_id] = function_module
  268. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  269. valves = Functions.get_function_valves_by_id(action_id)
  270. function_module.valves = function_module.Valves(**(valves if valves else {}))
  271. if hasattr(function_module, "action"):
  272. try:
  273. action = function_module.action
  274. # Get the signature of the function
  275. sig = inspect.signature(action)
  276. params = {"body": data}
  277. # Extra parameters to be passed to the function
  278. extra_params = {
  279. "__model__": model,
  280. "__id__": sub_action_id if sub_action_id is not None else action_id,
  281. "__event_emitter__": __event_emitter__,
  282. "__event_call__": __event_call__,
  283. }
  284. # Add extra params in contained in function signature
  285. for key, value in extra_params.items():
  286. if key in sig.parameters:
  287. params[key] = value
  288. if "__user__" in sig.parameters:
  289. __user__ = {
  290. "id": user.id,
  291. "email": user.email,
  292. "name": user.name,
  293. "role": user.role,
  294. }
  295. try:
  296. if hasattr(function_module, "UserValves"):
  297. __user__["valves"] = function_module.UserValves(
  298. **Functions.get_user_valves_by_id_and_user_id(
  299. action_id, user.id
  300. )
  301. )
  302. except Exception as e:
  303. print(e)
  304. params = {**params, "__user__": __user__}
  305. if inspect.iscoroutinefunction(action):
  306. data = await action(**params)
  307. else:
  308. data = action(**params)
  309. except Exception as e:
  310. return Exception(f"Error: {e}")
  311. return data