middleware.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  1. import time
  2. import logging
  3. import sys
  4. import asyncio
  5. from aiocache import cached
  6. from typing import Any, Optional
  7. import random
  8. import json
  9. import html
  10. import inspect
  11. import re
  12. from uuid import uuid4
  13. from concurrent.futures import ThreadPoolExecutor
  14. from fastapi import Request
  15. from fastapi import BackgroundTasks
  16. from starlette.responses import Response, StreamingResponse
  17. from open_webui.models.chats import Chats
  18. from open_webui.models.users import Users
  19. from open_webui.socket.main import (
  20. get_event_call,
  21. get_event_emitter,
  22. get_active_status_by_user_id,
  23. )
  24. from open_webui.routers.tasks import (
  25. generate_queries,
  26. generate_title,
  27. generate_image_prompt,
  28. generate_chat_tags,
  29. )
  30. from open_webui.routers.retrieval import process_web_search, SearchForm
  31. from open_webui.routers.images import image_generations, GenerateImageForm
  32. from open_webui.utils.webhook import post_webhook
  33. from open_webui.models.users import UserModel
  34. from open_webui.models.functions import Functions
  35. from open_webui.models.models import Models
  36. from open_webui.retrieval.utils import get_sources_from_files
  37. from open_webui.utils.chat import generate_chat_completion
  38. from open_webui.utils.task import (
  39. get_task_model_id,
  40. rag_template,
  41. tools_function_calling_generation_template,
  42. )
  43. from open_webui.utils.misc import (
  44. get_message_list,
  45. add_or_update_system_message,
  46. add_or_update_user_message,
  47. get_last_user_message,
  48. get_last_assistant_message,
  49. prepend_to_first_user_message_content,
  50. )
  51. from open_webui.utils.tools import get_tools
  52. from open_webui.utils.plugin import load_function_module_by_id
  53. from open_webui.tasks import create_task
  54. from open_webui.config import (
  55. DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  56. DEFAULT_CODE_INTERPRETER_PROMPT,
  57. )
  58. from open_webui.env import (
  59. SRC_LOG_LEVELS,
  60. GLOBAL_LOG_LEVEL,
  61. BYPASS_MODEL_ACCESS_CONTROL,
  62. ENABLE_REALTIME_CHAT_SAVE,
  63. )
  64. from open_webui.constants import TASKS
  65. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  66. log = logging.getLogger(__name__)
  67. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  68. async def chat_completion_filter_functions_handler(request, body, model, extra_params):
  69. skip_files = None
  70. def get_filter_function_ids(model):
  71. def get_priority(function_id):
  72. function = Functions.get_function_by_id(function_id)
  73. if function is not None and hasattr(function, "valves"):
  74. # TODO: Fix FunctionModel
  75. return (function.valves if function.valves else {}).get("priority", 0)
  76. return 0
  77. filter_ids = [
  78. function.id for function in Functions.get_global_filter_functions()
  79. ]
  80. if "info" in model and "meta" in model["info"]:
  81. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  82. filter_ids = list(set(filter_ids))
  83. enabled_filter_ids = [
  84. function.id
  85. for function in Functions.get_functions_by_type("filter", active_only=True)
  86. ]
  87. filter_ids = [
  88. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  89. ]
  90. filter_ids.sort(key=get_priority)
  91. return filter_ids
  92. filter_ids = get_filter_function_ids(model)
  93. for filter_id in filter_ids:
  94. filter = Functions.get_function_by_id(filter_id)
  95. if not filter:
  96. continue
  97. if filter_id in request.app.state.FUNCTIONS:
  98. function_module = request.app.state.FUNCTIONS[filter_id]
  99. else:
  100. function_module, _, _ = load_function_module_by_id(filter_id)
  101. request.app.state.FUNCTIONS[filter_id] = function_module
  102. # Check if the function has a file_handler variable
  103. if hasattr(function_module, "file_handler"):
  104. skip_files = function_module.file_handler
  105. # Apply valves to the function
  106. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  107. valves = Functions.get_function_valves_by_id(filter_id)
  108. function_module.valves = function_module.Valves(
  109. **(valves if valves else {})
  110. )
  111. if hasattr(function_module, "inlet"):
  112. try:
  113. inlet = function_module.inlet
  114. # Create a dictionary of parameters to be passed to the function
  115. params = {"body": body} | {
  116. k: v
  117. for k, v in {
  118. **extra_params,
  119. "__model__": model,
  120. "__id__": filter_id,
  121. }.items()
  122. if k in inspect.signature(inlet).parameters
  123. }
  124. if "__user__" in params and hasattr(function_module, "UserValves"):
  125. try:
  126. params["__user__"]["valves"] = function_module.UserValves(
  127. **Functions.get_user_valves_by_id_and_user_id(
  128. filter_id, params["__user__"]["id"]
  129. )
  130. )
  131. except Exception as e:
  132. print(e)
  133. if inspect.iscoroutinefunction(inlet):
  134. body = await inlet(**params)
  135. else:
  136. body = inlet(**params)
  137. except Exception as e:
  138. print(f"Error: {e}")
  139. raise e
  140. if skip_files and "files" in body.get("metadata", {}):
  141. del body["metadata"]["files"]
  142. return body, {}
  143. async def chat_completion_tools_handler(
  144. request: Request, body: dict, user: UserModel, models, extra_params: dict
  145. ) -> tuple[dict, dict]:
  146. async def get_content_from_response(response) -> Optional[str]:
  147. content = None
  148. if hasattr(response, "body_iterator"):
  149. async for chunk in response.body_iterator:
  150. data = json.loads(chunk.decode("utf-8"))
  151. content = data["choices"][0]["message"]["content"]
  152. # Cleanup any remaining background tasks if necessary
  153. if response.background is not None:
  154. await response.background()
  155. else:
  156. content = response["choices"][0]["message"]["content"]
  157. return content
  158. def get_tools_function_calling_payload(messages, task_model_id, content):
  159. user_message = get_last_user_message(messages)
  160. history = "\n".join(
  161. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  162. for message in messages[::-1][:4]
  163. )
  164. prompt = f"History:\n{history}\nQuery: {user_message}"
  165. return {
  166. "model": task_model_id,
  167. "messages": [
  168. {"role": "system", "content": content},
  169. {"role": "user", "content": f"Query: {prompt}"},
  170. ],
  171. "stream": False,
  172. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  173. }
  174. # If tool_ids field is present, call the functions
  175. metadata = body.get("metadata", {})
  176. tool_ids = metadata.get("tool_ids", None)
  177. log.debug(f"{tool_ids=}")
  178. if not tool_ids:
  179. return body, {}
  180. skip_files = False
  181. sources = []
  182. task_model_id = get_task_model_id(
  183. body["model"],
  184. request.app.state.config.TASK_MODEL,
  185. request.app.state.config.TASK_MODEL_EXTERNAL,
  186. models,
  187. )
  188. tools = get_tools(
  189. request,
  190. tool_ids,
  191. user,
  192. {
  193. **extra_params,
  194. "__model__": models[task_model_id],
  195. "__messages__": body["messages"],
  196. "__files__": metadata.get("files", []),
  197. },
  198. )
  199. log.info(f"{tools=}")
  200. specs = [tool["spec"] for tool in tools.values()]
  201. tools_specs = json.dumps(specs)
  202. if request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  203. template = request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  204. else:
  205. template = DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  206. tools_function_calling_prompt = tools_function_calling_generation_template(
  207. template, tools_specs
  208. )
  209. log.info(f"{tools_function_calling_prompt=}")
  210. payload = get_tools_function_calling_payload(
  211. body["messages"], task_model_id, tools_function_calling_prompt
  212. )
  213. try:
  214. response = await generate_chat_completion(request, form_data=payload, user=user)
  215. log.debug(f"{response=}")
  216. content = await get_content_from_response(response)
  217. log.debug(f"{content=}")
  218. if not content:
  219. return body, {}
  220. try:
  221. content = content[content.find("{") : content.rfind("}") + 1]
  222. if not content:
  223. raise Exception("No JSON object found in the response")
  224. result = json.loads(content)
  225. async def tool_call_handler(tool_call):
  226. log.debug(f"{tool_call=}")
  227. tool_function_name = tool_call.get("name", None)
  228. if tool_function_name not in tools:
  229. return body, {}
  230. tool_function_params = tool_call.get("parameters", {})
  231. try:
  232. required_params = (
  233. tools[tool_function_name]
  234. .get("spec", {})
  235. .get("parameters", {})
  236. .get("required", [])
  237. )
  238. tool_function = tools[tool_function_name]["callable"]
  239. tool_function_params = {
  240. k: v
  241. for k, v in tool_function_params.items()
  242. if k in required_params
  243. }
  244. tool_output = await tool_function(**tool_function_params)
  245. except Exception as e:
  246. tool_output = str(e)
  247. if isinstance(tool_output, str):
  248. if tools[tool_function_name]["citation"]:
  249. sources.append(
  250. {
  251. "source": {
  252. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  253. },
  254. "document": [tool_output],
  255. "metadata": [
  256. {
  257. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  258. }
  259. ],
  260. }
  261. )
  262. else:
  263. sources.append(
  264. {
  265. "source": {},
  266. "document": [tool_output],
  267. "metadata": [
  268. {
  269. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  270. }
  271. ],
  272. }
  273. )
  274. if tools[tool_function_name]["file_handler"]:
  275. skip_files = True
  276. # check if "tool_calls" in result
  277. if result.get("tool_calls"):
  278. for tool_call in result.get("tool_calls"):
  279. await tool_call_handler(tool_call)
  280. else:
  281. await tool_call_handler(result)
  282. except Exception as e:
  283. log.exception(f"Error: {e}")
  284. content = None
  285. except Exception as e:
  286. log.exception(f"Error: {e}")
  287. content = None
  288. log.debug(f"tool_contexts: {sources}")
  289. if skip_files and "files" in body.get("metadata", {}):
  290. del body["metadata"]["files"]
  291. return body, {"sources": sources}
  292. async def chat_web_search_handler(
  293. request: Request, form_data: dict, extra_params: dict, user
  294. ):
  295. event_emitter = extra_params["__event_emitter__"]
  296. await event_emitter(
  297. {
  298. "type": "status",
  299. "data": {
  300. "action": "web_search",
  301. "description": "Generating search query",
  302. "done": False,
  303. },
  304. }
  305. )
  306. messages = form_data["messages"]
  307. user_message = get_last_user_message(messages)
  308. queries = []
  309. try:
  310. res = await generate_queries(
  311. request,
  312. {
  313. "model": form_data["model"],
  314. "messages": messages,
  315. "prompt": user_message,
  316. "type": "web_search",
  317. },
  318. user,
  319. )
  320. response = res["choices"][0]["message"]["content"]
  321. try:
  322. bracket_start = response.find("{")
  323. bracket_end = response.rfind("}") + 1
  324. if bracket_start == -1 or bracket_end == -1:
  325. raise Exception("No JSON object found in the response")
  326. response = response[bracket_start:bracket_end]
  327. queries = json.loads(response)
  328. queries = queries.get("queries", [])
  329. except Exception as e:
  330. queries = [response]
  331. except Exception as e:
  332. log.exception(e)
  333. queries = [user_message]
  334. if len(queries) == 0:
  335. await event_emitter(
  336. {
  337. "type": "status",
  338. "data": {
  339. "action": "web_search",
  340. "description": "No search query generated",
  341. "done": True,
  342. },
  343. }
  344. )
  345. return
  346. searchQuery = queries[0]
  347. await event_emitter(
  348. {
  349. "type": "status",
  350. "data": {
  351. "action": "web_search",
  352. "description": 'Searching "{{searchQuery}}"',
  353. "query": searchQuery,
  354. "done": False,
  355. },
  356. }
  357. )
  358. try:
  359. results = await process_web_search(
  360. request,
  361. SearchForm(
  362. **{
  363. "query": searchQuery,
  364. }
  365. ),
  366. extra_params=extra_params,
  367. user=user
  368. )
  369. if results:
  370. await event_emitter(
  371. {
  372. "type": "status",
  373. "data": {
  374. "action": "web_search",
  375. "description": "Searched {{count}} sites",
  376. "query": searchQuery,
  377. "urls": results["filenames"],
  378. "done": True,
  379. },
  380. }
  381. )
  382. files = form_data.get("files", [])
  383. files.append(
  384. {
  385. "collection_name": results["collection_name"],
  386. "name": searchQuery,
  387. "type": "web_search_results",
  388. "urls": results["filenames"],
  389. }
  390. )
  391. form_data["files"] = files
  392. else:
  393. await event_emitter(
  394. {
  395. "type": "status",
  396. "data": {
  397. "action": "web_search",
  398. "description": "No search results found",
  399. "query": searchQuery,
  400. "done": True,
  401. "error": True,
  402. },
  403. }
  404. )
  405. except Exception as e:
  406. log.exception(e)
  407. await event_emitter(
  408. {
  409. "type": "status",
  410. "data": {
  411. "action": "web_search",
  412. "description": 'Error searching "{{searchQuery}}"',
  413. "query": searchQuery,
  414. "done": True,
  415. "error": True,
  416. },
  417. }
  418. )
  419. return form_data
  420. async def chat_image_generation_handler(
  421. request: Request, form_data: dict, extra_params: dict, user
  422. ):
  423. __event_emitter__ = extra_params["__event_emitter__"]
  424. await __event_emitter__(
  425. {
  426. "type": "status",
  427. "data": {"description": "Generating an image", "done": False},
  428. }
  429. )
  430. messages = form_data["messages"]
  431. user_message = get_last_user_message(messages)
  432. prompt = user_message
  433. negative_prompt = ""
  434. if request.app.state.config.ENABLE_IMAGE_PROMPT_GENERATION:
  435. try:
  436. res = await generate_image_prompt(
  437. request,
  438. {
  439. "model": form_data["model"],
  440. "messages": messages,
  441. },
  442. user,
  443. )
  444. response = res["choices"][0]["message"]["content"]
  445. try:
  446. bracket_start = response.find("{")
  447. bracket_end = response.rfind("}") + 1
  448. if bracket_start == -1 or bracket_end == -1:
  449. raise Exception("No JSON object found in the response")
  450. response = response[bracket_start:bracket_end]
  451. response = json.loads(response)
  452. prompt = response.get("prompt", [])
  453. except Exception as e:
  454. prompt = user_message
  455. except Exception as e:
  456. log.exception(e)
  457. prompt = user_message
  458. system_message_content = ""
  459. try:
  460. images = await image_generations(
  461. request=request,
  462. form_data=GenerateImageForm(**{"prompt": prompt}),
  463. user=user,
  464. )
  465. await __event_emitter__(
  466. {
  467. "type": "status",
  468. "data": {"description": "Generated an image", "done": True},
  469. }
  470. )
  471. for image in images:
  472. await __event_emitter__(
  473. {
  474. "type": "message",
  475. "data": {"content": f"![Generated Image]({image['url']})\n"},
  476. }
  477. )
  478. system_message_content = "<context>User is shown the generated image, tell the user that the image has been generated</context>"
  479. except Exception as e:
  480. log.exception(e)
  481. await __event_emitter__(
  482. {
  483. "type": "status",
  484. "data": {
  485. "description": f"An error occured while generating an image",
  486. "done": True,
  487. },
  488. }
  489. )
  490. system_message_content = "<context>Unable to generate an image, tell the user that an error occured</context>"
  491. if system_message_content:
  492. form_data["messages"] = add_or_update_system_message(
  493. system_message_content, form_data["messages"]
  494. )
  495. return form_data
  496. async def chat_completion_files_handler(
  497. request: Request, body: dict, user: UserModel
  498. ) -> tuple[dict, dict[str, list]]:
  499. sources = []
  500. if files := body.get("metadata", {}).get("files", None):
  501. try:
  502. queries_response = await generate_queries(
  503. request,
  504. {
  505. "model": body["model"],
  506. "messages": body["messages"],
  507. "type": "retrieval",
  508. },
  509. user,
  510. )
  511. queries_response = queries_response["choices"][0]["message"]["content"]
  512. try:
  513. bracket_start = queries_response.find("{")
  514. bracket_end = queries_response.rfind("}") + 1
  515. if bracket_start == -1 or bracket_end == -1:
  516. raise Exception("No JSON object found in the response")
  517. queries_response = queries_response[bracket_start:bracket_end]
  518. queries_response = json.loads(queries_response)
  519. except Exception as e:
  520. queries_response = {"queries": [queries_response]}
  521. queries = queries_response.get("queries", [])
  522. except Exception as e:
  523. queries = []
  524. if len(queries) == 0:
  525. queries = [get_last_user_message(body["messages"])]
  526. try:
  527. # Offload get_sources_from_files to a separate thread
  528. loop = asyncio.get_running_loop()
  529. with ThreadPoolExecutor() as executor:
  530. sources = await loop.run_in_executor(
  531. executor,
  532. lambda: get_sources_from_files(
  533. files=files,
  534. queries=queries,
  535. embedding_function=request.app.state.EMBEDDING_FUNCTION,
  536. k=request.app.state.config.TOP_K,
  537. reranking_function=request.app.state.rf,
  538. r=request.app.state.config.RELEVANCE_THRESHOLD,
  539. hybrid_search=request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  540. ),
  541. )
  542. except Exception as e:
  543. log.exception(e)
  544. log.debug(f"rag_contexts:sources: {sources}")
  545. return body, {"sources": sources}
  546. def apply_params_to_form_data(form_data, model):
  547. params = form_data.pop("params", {})
  548. if model.get("ollama"):
  549. form_data["options"] = params
  550. if "format" in params:
  551. form_data["format"] = params["format"]
  552. if "keep_alive" in params:
  553. form_data["keep_alive"] = params["keep_alive"]
  554. else:
  555. if "seed" in params:
  556. form_data["seed"] = params["seed"]
  557. if "stop" in params:
  558. form_data["stop"] = params["stop"]
  559. if "temperature" in params:
  560. form_data["temperature"] = params["temperature"]
  561. if "max_tokens" in params:
  562. form_data["max_tokens"] = params["max_tokens"]
  563. if "top_p" in params:
  564. form_data["top_p"] = params["top_p"]
  565. if "frequency_penalty" in params:
  566. form_data["frequency_penalty"] = params["frequency_penalty"]
  567. if "reasoning_effort" in params:
  568. form_data["reasoning_effort"] = params["reasoning_effort"]
  569. return form_data
  570. async def process_chat_payload(request, form_data, metadata, user, model):
  571. form_data = apply_params_to_form_data(form_data, model)
  572. log.debug(f"form_data: {form_data}")
  573. event_emitter = get_event_emitter(metadata)
  574. event_call = get_event_call(metadata)
  575. extra_params = {
  576. "__event_emitter__": event_emitter,
  577. "__event_call__": event_call,
  578. "__user__": {
  579. "id": user.id,
  580. "email": user.email,
  581. "name": user.name,
  582. "role": user.role,
  583. },
  584. "__metadata__": metadata,
  585. "__request__": request,
  586. }
  587. # Initialize events to store additional event to be sent to the client
  588. # Initialize contexts and citation
  589. models = request.app.state.MODELS
  590. events = []
  591. sources = []
  592. user_message = get_last_user_message(form_data["messages"])
  593. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  594. if model_knowledge:
  595. await event_emitter(
  596. {
  597. "type": "status",
  598. "data": {
  599. "action": "knowledge_search",
  600. "query": user_message,
  601. "done": False,
  602. },
  603. }
  604. )
  605. knowledge_files = []
  606. for item in model_knowledge:
  607. if item.get("collection_name"):
  608. knowledge_files.append(
  609. {
  610. "id": item.get("collection_name"),
  611. "name": item.get("name"),
  612. "legacy": True,
  613. }
  614. )
  615. elif item.get("collection_names"):
  616. knowledge_files.append(
  617. {
  618. "name": item.get("name"),
  619. "type": "collection",
  620. "collection_names": item.get("collection_names"),
  621. "legacy": True,
  622. }
  623. )
  624. else:
  625. knowledge_files.append(item)
  626. files = form_data.get("files", [])
  627. files.extend(knowledge_files)
  628. form_data["files"] = files
  629. variables = form_data.pop("variables", None)
  630. features = form_data.pop("features", None)
  631. if features:
  632. if "web_search" in features and features["web_search"]:
  633. form_data = await chat_web_search_handler(
  634. request, form_data, extra_params, user
  635. )
  636. if "image_generation" in features and features["image_generation"]:
  637. form_data = await chat_image_generation_handler(
  638. request, form_data, extra_params, user
  639. )
  640. if "code_interpreter" in features and features["code_interpreter"]:
  641. form_data["messages"] = add_or_update_user_message(
  642. DEFAULT_CODE_INTERPRETER_PROMPT, form_data["messages"]
  643. )
  644. try:
  645. form_data, flags = await chat_completion_filter_functions_handler(
  646. request, form_data, model, extra_params
  647. )
  648. except Exception as e:
  649. raise Exception(f"Error: {e}")
  650. tool_ids = form_data.pop("tool_ids", None)
  651. files = form_data.pop("files", None)
  652. # Remove files duplicates
  653. if files:
  654. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  655. metadata = {
  656. **metadata,
  657. "tool_ids": tool_ids,
  658. "files": files,
  659. }
  660. form_data["metadata"] = metadata
  661. try:
  662. form_data, flags = await chat_completion_tools_handler(
  663. request, form_data, user, models, extra_params
  664. )
  665. sources.extend(flags.get("sources", []))
  666. except Exception as e:
  667. log.exception(e)
  668. try:
  669. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  670. sources.extend(flags.get("sources", []))
  671. except Exception as e:
  672. log.exception(e)
  673. # If context is not empty, insert it into the messages
  674. if len(sources) > 0:
  675. context_string = ""
  676. for source_idx, source in enumerate(sources):
  677. source_id = source.get("source", {}).get("name", "")
  678. if "document" in source:
  679. for doc_idx, doc_context in enumerate(source["document"]):
  680. metadata = source.get("metadata")
  681. doc_source_id = None
  682. if metadata:
  683. doc_source_id = metadata[doc_idx].get("source", source_id)
  684. if source_id:
  685. context_string += f"<source><source_id>{doc_source_id if doc_source_id is not None else source_id}</source_id><source_context>{doc_context}</source_context></source>\n"
  686. else:
  687. # If there is no source_id, then do not include the source_id tag
  688. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  689. context_string = context_string.strip()
  690. prompt = get_last_user_message(form_data["messages"])
  691. if prompt is None:
  692. raise Exception("No user message found")
  693. if (
  694. request.app.state.config.RELEVANCE_THRESHOLD == 0
  695. and context_string.strip() == ""
  696. ):
  697. log.debug(
  698. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  699. )
  700. # Workaround for Ollama 2.0+ system prompt issue
  701. # TODO: replace with add_or_update_system_message
  702. if model["owned_by"] == "ollama":
  703. form_data["messages"] = prepend_to_first_user_message_content(
  704. rag_template(
  705. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  706. ),
  707. form_data["messages"],
  708. )
  709. else:
  710. form_data["messages"] = add_or_update_system_message(
  711. rag_template(
  712. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  713. ),
  714. form_data["messages"],
  715. )
  716. # If there are citations, add them to the data_items
  717. sources = [source for source in sources if source.get("source", {}).get("name", "")]
  718. if len(sources) > 0:
  719. events.append({"sources": sources})
  720. if model_knowledge:
  721. await event_emitter(
  722. {
  723. "type": "status",
  724. "data": {
  725. "action": "knowledge_search",
  726. "query": user_message,
  727. "done": True,
  728. "hidden": True,
  729. },
  730. }
  731. )
  732. return form_data, events
  733. async def process_chat_response(
  734. request, response, form_data, user, events, metadata, tasks
  735. ):
  736. async def background_tasks_handler():
  737. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  738. message = message_map.get(metadata["message_id"]) if message_map else None
  739. if message:
  740. messages = get_message_list(message_map, message.get("id"))
  741. if tasks:
  742. if TASKS.TITLE_GENERATION in tasks:
  743. if tasks[TASKS.TITLE_GENERATION]:
  744. res = await generate_title(
  745. request,
  746. {
  747. "model": message["model"],
  748. "messages": messages,
  749. "chat_id": metadata["chat_id"],
  750. },
  751. user,
  752. )
  753. if res and isinstance(res, dict):
  754. if len(res.get("choices", [])) == 1:
  755. title_string = (
  756. res.get("choices", [])[0]
  757. .get("message", {})
  758. .get("content", message.get("content", "New Chat"))
  759. )
  760. else:
  761. title_string = ""
  762. title_string = title_string[
  763. title_string.find("{") : title_string.rfind("}") + 1
  764. ]
  765. try:
  766. title = json.loads(title_string).get(
  767. "title", "New Chat"
  768. )
  769. except Exception as e:
  770. title = ""
  771. if not title:
  772. title = messages[0].get("content", "New Chat")
  773. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  774. await event_emitter(
  775. {
  776. "type": "chat:title",
  777. "data": title,
  778. }
  779. )
  780. elif len(messages) == 2:
  781. title = messages[0].get("content", "New Chat")
  782. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  783. await event_emitter(
  784. {
  785. "type": "chat:title",
  786. "data": message.get("content", "New Chat"),
  787. }
  788. )
  789. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  790. res = await generate_chat_tags(
  791. request,
  792. {
  793. "model": message["model"],
  794. "messages": messages,
  795. "chat_id": metadata["chat_id"],
  796. },
  797. user,
  798. )
  799. if res and isinstance(res, dict):
  800. if len(res.get("choices", [])) == 1:
  801. tags_string = (
  802. res.get("choices", [])[0]
  803. .get("message", {})
  804. .get("content", "")
  805. )
  806. else:
  807. tags_string = ""
  808. tags_string = tags_string[
  809. tags_string.find("{") : tags_string.rfind("}") + 1
  810. ]
  811. try:
  812. tags = json.loads(tags_string).get("tags", [])
  813. Chats.update_chat_tags_by_id(
  814. metadata["chat_id"], tags, user
  815. )
  816. await event_emitter(
  817. {
  818. "type": "chat:tags",
  819. "data": tags,
  820. }
  821. )
  822. except Exception as e:
  823. pass
  824. event_emitter = None
  825. event_caller = None
  826. if (
  827. "session_id" in metadata
  828. and metadata["session_id"]
  829. and "chat_id" in metadata
  830. and metadata["chat_id"]
  831. and "message_id" in metadata
  832. and metadata["message_id"]
  833. ):
  834. event_emitter = get_event_emitter(metadata)
  835. event_caller = get_event_call(metadata)
  836. # Non-streaming response
  837. if not isinstance(response, StreamingResponse):
  838. if event_emitter:
  839. if "selected_model_id" in response:
  840. Chats.upsert_message_to_chat_by_id_and_message_id(
  841. metadata["chat_id"],
  842. metadata["message_id"],
  843. {
  844. "selectedModelId": response["selected_model_id"],
  845. },
  846. )
  847. if response.get("choices", [])[0].get("message", {}).get("content"):
  848. content = response["choices"][0]["message"]["content"]
  849. if content:
  850. await event_emitter(
  851. {
  852. "type": "chat:completion",
  853. "data": response,
  854. }
  855. )
  856. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  857. await event_emitter(
  858. {
  859. "type": "chat:completion",
  860. "data": {
  861. "done": True,
  862. "content": content,
  863. "title": title,
  864. },
  865. }
  866. )
  867. # Save message in the database
  868. Chats.upsert_message_to_chat_by_id_and_message_id(
  869. metadata["chat_id"],
  870. metadata["message_id"],
  871. {
  872. "content": content,
  873. },
  874. )
  875. # Send a webhook notification if the user is not active
  876. if get_active_status_by_user_id(user.id) is None:
  877. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  878. if webhook_url:
  879. post_webhook(
  880. webhook_url,
  881. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  882. {
  883. "action": "chat",
  884. "message": content,
  885. "title": title,
  886. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  887. },
  888. )
  889. await background_tasks_handler()
  890. return response
  891. else:
  892. return response
  893. # Non standard response
  894. if not any(
  895. content_type in response.headers["Content-Type"]
  896. for content_type in ["text/event-stream", "application/x-ndjson"]
  897. ):
  898. return response
  899. # Streaming response
  900. if event_emitter and event_caller:
  901. task_id = str(uuid4()) # Create a unique task ID.
  902. model_id = form_data.get("model", "")
  903. # Handle as a background task
  904. async def post_response_handler(response, events):
  905. def serialize_content_blocks(content_blocks, raw=False):
  906. content = ""
  907. for block in content_blocks:
  908. if block["type"] == "text":
  909. content = f"{content}{block['content'].strip()}\n"
  910. elif block["type"] == "reasoning":
  911. reasoning_display_content = "\n".join(
  912. (f"> {line}" if not line.startswith(">") else line)
  913. for line in block["content"].splitlines()
  914. )
  915. reasoning_duration = block.get("duration", None)
  916. if reasoning_duration:
  917. content = f'{content}<details type="reasoning" done="true" duration="{reasoning_duration}">\n<summary>Thought for {reasoning_duration} seconds</summary>\n{reasoning_display_content}\n</details>\n'
  918. else:
  919. content = f'{content}<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  920. elif block["type"] == "code_interpreter":
  921. attributes = block.get("attributes", {})
  922. output = block.get("output", None)
  923. lang = attributes.get("lang", "")
  924. if output:
  925. output = html.escape(json.dumps(output))
  926. if raw:
  927. content = f'{content}<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n```output\n{output}\n```\n</details>\n'
  928. else:
  929. content = f'{content}<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  930. else:
  931. content = f'{content}<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  932. else:
  933. block_content = str(block["content"]).strip()
  934. content = f"{content}{block['type']}: {block_content}\n"
  935. return content
  936. def tag_content_handler(content_type, tags, content, content_blocks):
  937. end_flag = False
  938. def extract_attributes(tag_content):
  939. """Extract attributes from a tag if they exist."""
  940. attributes = {}
  941. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  942. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  943. for key, value in matches:
  944. attributes[key] = value
  945. return attributes
  946. if content_blocks[-1]["type"] == "text":
  947. for tag in tags:
  948. # Match start tag e.g., <tag> or <tag attr="value">
  949. start_tag_pattern = rf"<{tag}(.*?)>"
  950. match = re.search(start_tag_pattern, content)
  951. if match:
  952. # Extract attributes in the tag (if present)
  953. attributes = extract_attributes(match.group(1))
  954. # Remove the start tag from the currently handling text block
  955. content_blocks[-1]["content"] = content_blocks[-1][
  956. "content"
  957. ].replace(match.group(0), "")
  958. if not content_blocks[-1]["content"]:
  959. content_blocks.pop()
  960. # Append the new block
  961. content_blocks.append(
  962. {
  963. "type": content_type,
  964. "tag": tag,
  965. "attributes": attributes,
  966. "content": "",
  967. "started_at": time.time(),
  968. }
  969. )
  970. break
  971. elif content_blocks[-1]["type"] == content_type:
  972. tag = content_blocks[-1]["tag"]
  973. # Match end tag e.g., </tag>
  974. end_tag_pattern = rf"</{tag}>"
  975. if re.search(end_tag_pattern, content):
  976. block_content = content_blocks[-1]["content"]
  977. # Strip start and end tags from the content
  978. start_tag_pattern = rf"<{tag}(.*?)>"
  979. block_content = re.sub(
  980. start_tag_pattern, "", block_content
  981. ).strip()
  982. block_content = re.sub(
  983. end_tag_pattern, "", block_content
  984. ).strip()
  985. if block_content:
  986. end_flag = True
  987. content_blocks[-1]["content"] = block_content
  988. content_blocks[-1]["ended_at"] = time.time()
  989. content_blocks[-1]["duration"] = int(
  990. content_blocks[-1]["ended_at"]
  991. - content_blocks[-1]["started_at"]
  992. )
  993. # Reset the content_blocks by appending a new text block
  994. content_blocks.append(
  995. {
  996. "type": "text",
  997. "content": "",
  998. }
  999. )
  1000. # Clean processed content
  1001. content = re.sub(
  1002. rf"<{tag}(.*?)>(.|\n)*?</{tag}>",
  1003. "",
  1004. content,
  1005. flags=re.DOTALL,
  1006. )
  1007. else:
  1008. # Remove the block if content is empty
  1009. content_blocks.pop()
  1010. return content, content_blocks, end_flag
  1011. message = Chats.get_message_by_id_and_message_id(
  1012. metadata["chat_id"], metadata["message_id"]
  1013. )
  1014. content = message.get("content", "") if message else ""
  1015. content_blocks = [
  1016. {
  1017. "type": "text",
  1018. "content": content,
  1019. }
  1020. ]
  1021. # We might want to disable this by default
  1022. DETECT_REASONING = True
  1023. DETECT_CODE_INTERPRETER = True
  1024. reasoning_tags = ["think", "reason", "reasoning", "thought", "Thought"]
  1025. code_interpreter_tags = ["code_interpreter"]
  1026. try:
  1027. for event in events:
  1028. await event_emitter(
  1029. {
  1030. "type": "chat:completion",
  1031. "data": event,
  1032. }
  1033. )
  1034. # Save message in the database
  1035. Chats.upsert_message_to_chat_by_id_and_message_id(
  1036. metadata["chat_id"],
  1037. metadata["message_id"],
  1038. {
  1039. **event,
  1040. },
  1041. )
  1042. async def stream_body_handler(response):
  1043. nonlocal content
  1044. nonlocal content_blocks
  1045. async for line in response.body_iterator:
  1046. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1047. data = line
  1048. # Skip empty lines
  1049. if not data.strip():
  1050. continue
  1051. # "data:" is the prefix for each event
  1052. if not data.startswith("data:"):
  1053. continue
  1054. # Remove the prefix
  1055. data = data[len("data:") :].strip()
  1056. try:
  1057. data = json.loads(data)
  1058. if "selected_model_id" in data:
  1059. model_id = data["selected_model_id"]
  1060. Chats.upsert_message_to_chat_by_id_and_message_id(
  1061. metadata["chat_id"],
  1062. metadata["message_id"],
  1063. {
  1064. "selectedModelId": model_id,
  1065. },
  1066. )
  1067. else:
  1068. choices = data.get("choices", [])
  1069. if not choices:
  1070. continue
  1071. value = choices[0].get("delta", {}).get("content")
  1072. if value:
  1073. content = f"{content}{value}"
  1074. content_blocks[-1]["content"] = (
  1075. content_blocks[-1]["content"] + value
  1076. )
  1077. if DETECT_REASONING:
  1078. content, content_blocks, _ = (
  1079. tag_content_handler(
  1080. "reasoning",
  1081. reasoning_tags,
  1082. content,
  1083. content_blocks,
  1084. )
  1085. )
  1086. if DETECT_CODE_INTERPRETER:
  1087. content, content_blocks, end = (
  1088. tag_content_handler(
  1089. "code_interpreter",
  1090. code_interpreter_tags,
  1091. content,
  1092. content_blocks,
  1093. )
  1094. )
  1095. if end:
  1096. break
  1097. if ENABLE_REALTIME_CHAT_SAVE:
  1098. # Save message in the database
  1099. Chats.upsert_message_to_chat_by_id_and_message_id(
  1100. metadata["chat_id"],
  1101. metadata["message_id"],
  1102. {
  1103. "content": serialize_content_blocks(
  1104. content_blocks
  1105. ),
  1106. },
  1107. )
  1108. else:
  1109. data = {
  1110. "content": serialize_content_blocks(
  1111. content_blocks
  1112. ),
  1113. }
  1114. await event_emitter(
  1115. {
  1116. "type": "chat:completion",
  1117. "data": data,
  1118. }
  1119. )
  1120. except Exception as e:
  1121. done = "data: [DONE]" in line
  1122. if done:
  1123. pass
  1124. else:
  1125. log.debug("Error: ", e)
  1126. continue
  1127. # Clean up the last text block
  1128. if content_blocks[-1]["type"] == "text":
  1129. content_blocks[-1]["content"] = content_blocks[-1][
  1130. "content"
  1131. ].strip()
  1132. if not content_blocks[-1]["content"]:
  1133. content_blocks.pop()
  1134. if response.background:
  1135. await response.background()
  1136. await stream_body_handler(response)
  1137. MAX_RETRIES = 5
  1138. retries = 0
  1139. while (
  1140. content_blocks[-1]["type"] == "code_interpreter"
  1141. and retries < MAX_RETRIES
  1142. ):
  1143. retries += 1
  1144. log.debug(f"Attempt count: {retries}")
  1145. try:
  1146. if content_blocks[-1]["attributes"].get("type") == "code":
  1147. output = await event_caller(
  1148. {
  1149. "type": "execute:python",
  1150. "data": {
  1151. "id": str(uuid4()),
  1152. "code": content_blocks[-1]["content"],
  1153. },
  1154. }
  1155. )
  1156. except Exception as e:
  1157. output = str(e)
  1158. content_blocks[-1]["output"] = output
  1159. content_blocks.append(
  1160. {
  1161. "type": "text",
  1162. "content": "",
  1163. }
  1164. )
  1165. await event_emitter(
  1166. {
  1167. "type": "chat:completion",
  1168. "data": {
  1169. "content": serialize_content_blocks(content_blocks),
  1170. },
  1171. }
  1172. )
  1173. try:
  1174. res = await generate_chat_completion(
  1175. request,
  1176. {
  1177. "model": model_id,
  1178. "stream": True,
  1179. "messages": [
  1180. *form_data["messages"],
  1181. {
  1182. "role": "assistant",
  1183. "content": serialize_content_blocks(
  1184. content_blocks, raw=True
  1185. ),
  1186. },
  1187. ],
  1188. },
  1189. user,
  1190. )
  1191. if isinstance(res, StreamingResponse):
  1192. await stream_body_handler(res)
  1193. else:
  1194. break
  1195. except Exception as e:
  1196. log.debug(e)
  1197. break
  1198. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1199. data = {
  1200. "done": True,
  1201. "content": serialize_content_blocks(content_blocks),
  1202. "title": title,
  1203. }
  1204. if not ENABLE_REALTIME_CHAT_SAVE:
  1205. # Save message in the database
  1206. Chats.upsert_message_to_chat_by_id_and_message_id(
  1207. metadata["chat_id"],
  1208. metadata["message_id"],
  1209. {
  1210. "content": serialize_content_blocks(content_blocks),
  1211. },
  1212. )
  1213. # Send a webhook notification if the user is not active
  1214. if get_active_status_by_user_id(user.id) is None:
  1215. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1216. if webhook_url:
  1217. post_webhook(
  1218. webhook_url,
  1219. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1220. {
  1221. "action": "chat",
  1222. "message": content,
  1223. "title": title,
  1224. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1225. },
  1226. )
  1227. await event_emitter(
  1228. {
  1229. "type": "chat:completion",
  1230. "data": data,
  1231. }
  1232. )
  1233. await background_tasks_handler()
  1234. except asyncio.CancelledError:
  1235. print("Task was cancelled!")
  1236. await event_emitter({"type": "task-cancelled"})
  1237. if not ENABLE_REALTIME_CHAT_SAVE:
  1238. # Save message in the database
  1239. Chats.upsert_message_to_chat_by_id_and_message_id(
  1240. metadata["chat_id"],
  1241. metadata["message_id"],
  1242. {
  1243. "content": serialize_content_blocks(content_blocks),
  1244. },
  1245. )
  1246. if response.background is not None:
  1247. await response.background()
  1248. # background_tasks.add_task(post_response_handler, response, events)
  1249. task_id, _ = create_task(post_response_handler(response, events))
  1250. return {"status": True, "task_id": task_id}
  1251. else:
  1252. # Fallback to the original response
  1253. async def stream_wrapper(original_generator, events):
  1254. def wrap_item(item):
  1255. return f"data: {item}\n\n"
  1256. for event in events:
  1257. yield wrap_item(json.dumps(event))
  1258. async for data in original_generator:
  1259. yield data
  1260. return StreamingResponse(
  1261. stream_wrapper(response.body_iterator, events),
  1262. headers=dict(response.headers),
  1263. background=response.background,
  1264. )