middleware.py 53 KB

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