middleware.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  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 inspect
  10. import re
  11. from uuid import uuid4
  12. from concurrent.futures import ThreadPoolExecutor
  13. from fastapi import Request
  14. from fastapi import BackgroundTasks
  15. from starlette.responses import Response, StreamingResponse
  16. from open_webui.models.chats import Chats
  17. from open_webui.models.users import Users
  18. from open_webui.socket.main import (
  19. get_event_call,
  20. get_event_emitter,
  21. get_active_status_by_user_id,
  22. )
  23. from open_webui.routers.tasks import (
  24. generate_queries,
  25. generate_title,
  26. generate_image_prompt,
  27. generate_chat_tags,
  28. )
  29. from open_webui.routers.retrieval import process_web_search, SearchForm
  30. from open_webui.routers.images import image_generations, GenerateImageForm
  31. from open_webui.utils.webhook import post_webhook
  32. from open_webui.models.users import UserModel
  33. from open_webui.models.functions import Functions
  34. from open_webui.models.models import Models
  35. from open_webui.retrieval.utils import get_sources_from_files
  36. from open_webui.utils.chat import generate_chat_completion
  37. from open_webui.utils.task import (
  38. get_task_model_id,
  39. rag_template,
  40. tools_function_calling_generation_template,
  41. )
  42. from open_webui.utils.misc import (
  43. get_message_list,
  44. add_or_update_system_message,
  45. get_last_user_message,
  46. get_last_assistant_message,
  47. prepend_to_first_user_message_content,
  48. )
  49. from open_webui.utils.tools import get_tools
  50. from open_webui.utils.plugin import load_function_module_by_id
  51. from open_webui.tasks import create_task
  52. from open_webui.config import DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  53. from open_webui.env import (
  54. SRC_LOG_LEVELS,
  55. GLOBAL_LOG_LEVEL,
  56. BYPASS_MODEL_ACCESS_CONTROL,
  57. ENABLE_REALTIME_CHAT_SAVE,
  58. )
  59. from open_webui.constants import TASKS
  60. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  61. log = logging.getLogger(__name__)
  62. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  63. async def chat_completion_filter_functions_handler(request, body, model, extra_params):
  64. skip_files = None
  65. def get_filter_function_ids(model):
  66. def get_priority(function_id):
  67. function = Functions.get_function_by_id(function_id)
  68. if function is not None and hasattr(function, "valves"):
  69. # TODO: Fix FunctionModel
  70. return (function.valves if function.valves else {}).get("priority", 0)
  71. return 0
  72. filter_ids = [
  73. function.id for function in Functions.get_global_filter_functions()
  74. ]
  75. if "info" in model and "meta" in model["info"]:
  76. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  77. filter_ids = list(set(filter_ids))
  78. enabled_filter_ids = [
  79. function.id
  80. for function in Functions.get_functions_by_type("filter", active_only=True)
  81. ]
  82. filter_ids = [
  83. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  84. ]
  85. filter_ids.sort(key=get_priority)
  86. return filter_ids
  87. filter_ids = get_filter_function_ids(model)
  88. for filter_id in filter_ids:
  89. filter = Functions.get_function_by_id(filter_id)
  90. if not filter:
  91. continue
  92. if filter_id in request.app.state.FUNCTIONS:
  93. function_module = request.app.state.FUNCTIONS[filter_id]
  94. else:
  95. function_module, _, _ = load_function_module_by_id(filter_id)
  96. request.app.state.FUNCTIONS[filter_id] = function_module
  97. # Check if the function has a file_handler variable
  98. if hasattr(function_module, "file_handler"):
  99. skip_files = function_module.file_handler
  100. # Apply valves to the function
  101. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  102. valves = Functions.get_function_valves_by_id(filter_id)
  103. function_module.valves = function_module.Valves(
  104. **(valves if valves else {})
  105. )
  106. if hasattr(function_module, "inlet"):
  107. try:
  108. inlet = function_module.inlet
  109. # Create a dictionary of parameters to be passed to the function
  110. params = {"body": body} | {
  111. k: v
  112. for k, v in {
  113. **extra_params,
  114. "__model__": model,
  115. "__id__": filter_id,
  116. }.items()
  117. if k in inspect.signature(inlet).parameters
  118. }
  119. if "__user__" in params and hasattr(function_module, "UserValves"):
  120. try:
  121. params["__user__"]["valves"] = function_module.UserValves(
  122. **Functions.get_user_valves_by_id_and_user_id(
  123. filter_id, params["__user__"]["id"]
  124. )
  125. )
  126. except Exception as e:
  127. print(e)
  128. if inspect.iscoroutinefunction(inlet):
  129. body = await inlet(**params)
  130. else:
  131. body = inlet(**params)
  132. except Exception as e:
  133. print(f"Error: {e}")
  134. raise e
  135. if skip_files and "files" in body.get("metadata", {}):
  136. del body["metadata"]["files"]
  137. return body, {}
  138. async def chat_completion_tools_handler(
  139. request: Request, body: dict, user: UserModel, models, extra_params: dict
  140. ) -> tuple[dict, dict]:
  141. async def get_content_from_response(response) -> Optional[str]:
  142. content = None
  143. if hasattr(response, "body_iterator"):
  144. async for chunk in response.body_iterator:
  145. data = json.loads(chunk.decode("utf-8"))
  146. content = data["choices"][0]["message"]["content"]
  147. # Cleanup any remaining background tasks if necessary
  148. if response.background is not None:
  149. await response.background()
  150. else:
  151. content = response["choices"][0]["message"]["content"]
  152. return content
  153. def get_tools_function_calling_payload(messages, task_model_id, content):
  154. user_message = get_last_user_message(messages)
  155. history = "\n".join(
  156. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  157. for message in messages[::-1][:4]
  158. )
  159. prompt = f"History:\n{history}\nQuery: {user_message}"
  160. return {
  161. "model": task_model_id,
  162. "messages": [
  163. {"role": "system", "content": content},
  164. {"role": "user", "content": f"Query: {prompt}"},
  165. ],
  166. "stream": False,
  167. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  168. }
  169. # If tool_ids field is present, call the functions
  170. metadata = body.get("metadata", {})
  171. tool_ids = metadata.get("tool_ids", None)
  172. log.debug(f"{tool_ids=}")
  173. if not tool_ids:
  174. return body, {}
  175. skip_files = False
  176. sources = []
  177. task_model_id = get_task_model_id(
  178. body["model"],
  179. request.app.state.config.TASK_MODEL,
  180. request.app.state.config.TASK_MODEL_EXTERNAL,
  181. models,
  182. )
  183. tools = get_tools(
  184. request,
  185. tool_ids,
  186. user,
  187. {
  188. **extra_params,
  189. "__model__": models[task_model_id],
  190. "__messages__": body["messages"],
  191. "__files__": metadata.get("files", []),
  192. },
  193. )
  194. log.info(f"{tools=}")
  195. specs = [tool["spec"] for tool in tools.values()]
  196. tools_specs = json.dumps(specs)
  197. if request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  198. template = request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  199. else:
  200. template = DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  201. tools_function_calling_prompt = tools_function_calling_generation_template(
  202. template, tools_specs
  203. )
  204. log.info(f"{tools_function_calling_prompt=}")
  205. payload = get_tools_function_calling_payload(
  206. body["messages"], task_model_id, tools_function_calling_prompt
  207. )
  208. try:
  209. response = await generate_chat_completion(request, form_data=payload, user=user)
  210. log.debug(f"{response=}")
  211. content = await get_content_from_response(response)
  212. log.debug(f"{content=}")
  213. if not content:
  214. return body, {}
  215. try:
  216. content = content[content.find("{") : content.rfind("}") + 1]
  217. if not content:
  218. raise Exception("No JSON object found in the response")
  219. result = json.loads(content)
  220. async def tool_call_handler(tool_call):
  221. log.debug(f"{tool_call=}")
  222. tool_function_name = tool_call.get("name", None)
  223. if tool_function_name not in tools:
  224. return body, {}
  225. tool_function_params = tool_call.get("parameters", {})
  226. try:
  227. required_params = (
  228. tools[tool_function_name]
  229. .get("spec", {})
  230. .get("parameters", {})
  231. .get("required", [])
  232. )
  233. tool_function = tools[tool_function_name]["callable"]
  234. tool_function_params = {
  235. k: v
  236. for k, v in tool_function_params.items()
  237. if k in required_params
  238. }
  239. tool_output = await tool_function(**tool_function_params)
  240. except Exception as e:
  241. tool_output = str(e)
  242. if isinstance(tool_output, str):
  243. if tools[tool_function_name]["citation"]:
  244. sources.append(
  245. {
  246. "source": {
  247. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  248. },
  249. "document": [tool_output],
  250. "metadata": [
  251. {
  252. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  253. }
  254. ],
  255. }
  256. )
  257. else:
  258. sources.append(
  259. {
  260. "source": {},
  261. "document": [tool_output],
  262. "metadata": [
  263. {
  264. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  265. }
  266. ],
  267. }
  268. )
  269. if tools[tool_function_name]["file_handler"]:
  270. skip_files = True
  271. # check if "tool_calls" in result
  272. if result.get("tool_calls"):
  273. for tool_call in result.get("tool_calls"):
  274. await tool_call_handler(tool_call)
  275. else:
  276. await tool_call_handler(result)
  277. except Exception as e:
  278. log.exception(f"Error: {e}")
  279. content = None
  280. except Exception as e:
  281. log.exception(f"Error: {e}")
  282. content = None
  283. log.debug(f"tool_contexts: {sources}")
  284. if skip_files and "files" in body.get("metadata", {}):
  285. del body["metadata"]["files"]
  286. return body, {"sources": sources}
  287. async def chat_web_search_handler(
  288. request: Request, form_data: dict, extra_params: dict, user
  289. ):
  290. event_emitter = extra_params["__event_emitter__"]
  291. await event_emitter(
  292. {
  293. "type": "status",
  294. "data": {
  295. "action": "web_search",
  296. "description": "Generating search query",
  297. "done": False,
  298. },
  299. }
  300. )
  301. messages = form_data["messages"]
  302. user_message = get_last_user_message(messages)
  303. queries = []
  304. try:
  305. res = await generate_queries(
  306. request,
  307. {
  308. "model": form_data["model"],
  309. "messages": messages,
  310. "prompt": user_message,
  311. "type": "web_search",
  312. },
  313. user,
  314. )
  315. response = res["choices"][0]["message"]["content"]
  316. try:
  317. bracket_start = response.find("{")
  318. bracket_end = response.rfind("}") + 1
  319. if bracket_start == -1 or bracket_end == -1:
  320. raise Exception("No JSON object found in the response")
  321. response = response[bracket_start:bracket_end]
  322. queries = json.loads(response)
  323. queries = queries.get("queries", [])
  324. except Exception as e:
  325. queries = [response]
  326. except Exception as e:
  327. log.exception(e)
  328. queries = [user_message]
  329. if len(queries) == 0:
  330. await event_emitter(
  331. {
  332. "type": "status",
  333. "data": {
  334. "action": "web_search",
  335. "description": "No search query generated",
  336. "done": True,
  337. },
  338. }
  339. )
  340. return
  341. searchQuery = queries[0]
  342. await event_emitter(
  343. {
  344. "type": "status",
  345. "data": {
  346. "action": "web_search",
  347. "description": 'Searching "{{searchQuery}}"',
  348. "query": searchQuery,
  349. "done": False,
  350. },
  351. }
  352. )
  353. try:
  354. # Offload process_web_search to a separate thread
  355. loop = asyncio.get_running_loop()
  356. with ThreadPoolExecutor() as executor:
  357. results = await loop.run_in_executor(
  358. executor,
  359. lambda: process_web_search(
  360. request,
  361. SearchForm(
  362. **{
  363. "query": searchQuery,
  364. }
  365. ),
  366. user,
  367. ),
  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. try:
  641. form_data, flags = await chat_completion_filter_functions_handler(
  642. request, form_data, model, extra_params
  643. )
  644. except Exception as e:
  645. raise Exception(f"Error: {e}")
  646. tool_ids = form_data.pop("tool_ids", None)
  647. files = form_data.pop("files", None)
  648. # Remove files duplicates
  649. if files:
  650. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  651. metadata = {
  652. **metadata,
  653. "tool_ids": tool_ids,
  654. "files": files,
  655. }
  656. form_data["metadata"] = metadata
  657. try:
  658. form_data, flags = await chat_completion_tools_handler(
  659. request, form_data, user, models, extra_params
  660. )
  661. sources.extend(flags.get("sources", []))
  662. except Exception as e:
  663. log.exception(e)
  664. try:
  665. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  666. sources.extend(flags.get("sources", []))
  667. except Exception as e:
  668. log.exception(e)
  669. # If context is not empty, insert it into the messages
  670. if len(sources) > 0:
  671. context_string = ""
  672. for source_idx, source in enumerate(sources):
  673. source_id = source.get("source", {}).get("name", "")
  674. if "document" in source:
  675. for doc_idx, doc_context in enumerate(source["document"]):
  676. metadata = source.get("metadata")
  677. doc_source_id = None
  678. if metadata:
  679. doc_source_id = metadata[doc_idx].get("source", source_id)
  680. if source_id:
  681. 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"
  682. else:
  683. # If there is no source_id, then do not include the source_id tag
  684. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  685. context_string = context_string.strip()
  686. prompt = get_last_user_message(form_data["messages"])
  687. if prompt is None:
  688. raise Exception("No user message found")
  689. if (
  690. request.app.state.config.RELEVANCE_THRESHOLD == 0
  691. and context_string.strip() == ""
  692. ):
  693. log.debug(
  694. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  695. )
  696. # Workaround for Ollama 2.0+ system prompt issue
  697. # TODO: replace with add_or_update_system_message
  698. if model["owned_by"] == "ollama":
  699. form_data["messages"] = prepend_to_first_user_message_content(
  700. rag_template(
  701. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  702. ),
  703. form_data["messages"],
  704. )
  705. else:
  706. form_data["messages"] = add_or_update_system_message(
  707. rag_template(
  708. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  709. ),
  710. form_data["messages"],
  711. )
  712. # If there are citations, add them to the data_items
  713. sources = [source for source in sources if source.get("source", {}).get("name", "")]
  714. if len(sources) > 0:
  715. events.append({"sources": sources})
  716. if model_knowledge:
  717. await event_emitter(
  718. {
  719. "type": "status",
  720. "data": {
  721. "action": "knowledge_search",
  722. "query": user_message,
  723. "done": True,
  724. "hidden": True,
  725. },
  726. }
  727. )
  728. return form_data, events
  729. async def process_chat_response(
  730. request, response, form_data, user, events, metadata, tasks
  731. ):
  732. async def background_tasks_handler():
  733. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  734. message = message_map.get(metadata["message_id"]) if message_map else None
  735. if message:
  736. messages = get_message_list(message_map, message.get("id"))
  737. if tasks:
  738. if TASKS.TITLE_GENERATION in tasks:
  739. if tasks[TASKS.TITLE_GENERATION]:
  740. res = await generate_title(
  741. request,
  742. {
  743. "model": message["model"],
  744. "messages": messages,
  745. "chat_id": metadata["chat_id"],
  746. },
  747. user,
  748. )
  749. if res and isinstance(res, dict):
  750. if len(res.get("choices", [])) == 1:
  751. title_string = (
  752. res.get("choices", [])[0]
  753. .get("message", {})
  754. .get("content", message.get("content", "New Chat"))
  755. )
  756. else:
  757. title_string = ""
  758. title_string = title_string[
  759. title_string.find("{") : title_string.rfind("}") + 1
  760. ]
  761. try:
  762. title = json.loads(title_string).get(
  763. "title", "New Chat"
  764. )
  765. except Exception as e:
  766. title = ""
  767. if not title:
  768. title = messages[0].get("content", "New Chat")
  769. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  770. await event_emitter(
  771. {
  772. "type": "chat:title",
  773. "data": title,
  774. }
  775. )
  776. elif len(messages) == 2:
  777. title = messages[0].get("content", "New Chat")
  778. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  779. await event_emitter(
  780. {
  781. "type": "chat:title",
  782. "data": message.get("content", "New Chat"),
  783. }
  784. )
  785. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  786. res = await generate_chat_tags(
  787. request,
  788. {
  789. "model": message["model"],
  790. "messages": messages,
  791. "chat_id": metadata["chat_id"],
  792. },
  793. user,
  794. )
  795. if res and isinstance(res, dict):
  796. if len(res.get("choices", [])) == 1:
  797. tags_string = (
  798. res.get("choices", [])[0]
  799. .get("message", {})
  800. .get("content", "")
  801. )
  802. else:
  803. tags_string = ""
  804. tags_string = tags_string[
  805. tags_string.find("{") : tags_string.rfind("}") + 1
  806. ]
  807. try:
  808. tags = json.loads(tags_string).get("tags", [])
  809. Chats.update_chat_tags_by_id(
  810. metadata["chat_id"], tags, user
  811. )
  812. await event_emitter(
  813. {
  814. "type": "chat:tags",
  815. "data": tags,
  816. }
  817. )
  818. except Exception as e:
  819. pass
  820. event_emitter = None
  821. event_caller = None
  822. if (
  823. "session_id" in metadata
  824. and metadata["session_id"]
  825. and "chat_id" in metadata
  826. and metadata["chat_id"]
  827. and "message_id" in metadata
  828. and metadata["message_id"]
  829. ):
  830. event_emitter = get_event_emitter(metadata)
  831. event_caller = get_event_call(metadata)
  832. # Non-streaming response
  833. if not isinstance(response, StreamingResponse):
  834. if event_emitter:
  835. if "selected_model_id" in response:
  836. Chats.upsert_message_to_chat_by_id_and_message_id(
  837. metadata["chat_id"],
  838. metadata["message_id"],
  839. {
  840. "selectedModelId": response["selected_model_id"],
  841. },
  842. )
  843. if response.get("choices", [])[0].get("message", {}).get("content"):
  844. content = response["choices"][0]["message"]["content"]
  845. if content:
  846. await event_emitter(
  847. {
  848. "type": "chat:completion",
  849. "data": response,
  850. }
  851. )
  852. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  853. await event_emitter(
  854. {
  855. "type": "chat:completion",
  856. "data": {
  857. "done": True,
  858. "content": content,
  859. "title": title,
  860. },
  861. }
  862. )
  863. # Save message in the database
  864. Chats.upsert_message_to_chat_by_id_and_message_id(
  865. metadata["chat_id"],
  866. metadata["message_id"],
  867. {
  868. "content": content,
  869. },
  870. )
  871. # Send a webhook notification if the user is not active
  872. if get_active_status_by_user_id(user.id) is None:
  873. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  874. if webhook_url:
  875. post_webhook(
  876. webhook_url,
  877. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  878. {
  879. "action": "chat",
  880. "message": content,
  881. "title": title,
  882. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  883. },
  884. )
  885. await background_tasks_handler()
  886. return response
  887. else:
  888. return response
  889. # Non standard response
  890. if not any(
  891. content_type in response.headers["Content-Type"]
  892. for content_type in ["text/event-stream", "application/x-ndjson"]
  893. ):
  894. return response
  895. # Streaming response
  896. if event_emitter and event_caller:
  897. task_id = str(uuid4()) # Create a unique task ID.
  898. model_id = form_data.get("model", "")
  899. # Handle as a background task
  900. async def post_response_handler(response, events):
  901. def serialize_content_blocks(content_blocks):
  902. content = ""
  903. for block in content_blocks:
  904. if block["type"] == "text":
  905. content = f"{content}{block['content'].strip()}\n"
  906. elif block["type"] == "reasoning":
  907. reasoning_display_content = "\n".join(
  908. (f"> {line}" if not line.startswith(">") else line)
  909. for line in block["content"].splitlines()
  910. )
  911. reasoning_duration = block.get("duration", None)
  912. if reasoning_duration:
  913. 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'
  914. else:
  915. content = f'{content}<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  916. elif block["type"] == "code_interpreter":
  917. attributes = block.get("attributes", {})
  918. lang = attributes.get("lang", "")
  919. attribute_type = attributes.get("type", "")
  920. content = f"{content}```{lang if lang else attribute_type}\n{block['content']}\n```\n"
  921. else:
  922. block_content = str(block["content"]).strip()
  923. content = f"{content}{block['type']}: {block_content}\n"
  924. return content
  925. def tag_content_handler(content_type, tags, content, content_blocks):
  926. def extract_attributes(tag_content):
  927. """Extract attributes from a tag if they exist."""
  928. attributes = {}
  929. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  930. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  931. for key, value in matches:
  932. attributes[key] = value
  933. return attributes
  934. if content_blocks[-1]["type"] == "text":
  935. for tag in tags:
  936. # Match start tag e.g., <tag> or <tag attr="value">
  937. start_tag_pattern = rf"<{tag}(.*?)>"
  938. match = re.search(start_tag_pattern, content)
  939. if match:
  940. # Extract attributes in the tag (if present)
  941. attributes = extract_attributes(match.group(1))
  942. # Remove the start tag from the currently handling text block
  943. content_blocks[-1]["content"] = content_blocks[-1][
  944. "content"
  945. ].replace(match.group(0), "")
  946. if not content_blocks[-1]["content"]:
  947. content_blocks.pop()
  948. # Append the new block
  949. content_blocks.append(
  950. {
  951. "type": content_type,
  952. "tag": tag,
  953. "attributes": attributes,
  954. "content": "",
  955. "started_at": time.time(),
  956. }
  957. )
  958. break
  959. elif content_blocks[-1]["type"] == content_type:
  960. tag = content_blocks[-1]["tag"]
  961. # Match end tag e.g., </tag>
  962. end_tag_pattern = rf"</{tag}>"
  963. if re.search(end_tag_pattern, content):
  964. block_content = content_blocks[-1]["content"]
  965. # Strip start and end tags from the content
  966. start_tag_pattern = rf"<{tag}(.*?)>"
  967. block_content = re.sub(
  968. start_tag_pattern, "", block_content
  969. ).strip()
  970. block_content = re.sub(
  971. end_tag_pattern, "", block_content
  972. ).strip()
  973. if block_content:
  974. content_blocks[-1]["content"] = block_content
  975. content_blocks[-1]["ended_at"] = time.time()
  976. content_blocks[-1]["duration"] = int(
  977. content_blocks[-1]["ended_at"]
  978. - content_blocks[-1]["started_at"]
  979. )
  980. # Reset the content_blocks by appending a new text block
  981. content_blocks.append(
  982. {
  983. "type": "text",
  984. "content": "",
  985. }
  986. )
  987. # Clean processed content
  988. content = re.sub(
  989. rf"<{tag}(.*?)>(.|\n)*?</{tag}>",
  990. "",
  991. content,
  992. flags=re.DOTALL,
  993. )
  994. else:
  995. # Remove the block if content is empty
  996. content_blocks.pop()
  997. return content, content_blocks
  998. message = Chats.get_message_by_id_and_message_id(
  999. metadata["chat_id"], metadata["message_id"]
  1000. )
  1001. content = message.get("content", "") if message else ""
  1002. content_blocks = [
  1003. {
  1004. "type": "text",
  1005. "content": content,
  1006. }
  1007. ]
  1008. # We might want to disable this by default
  1009. DETECT_REASONING = True
  1010. DETECT_CODE_INTERPRETER = True
  1011. reasoning_tags = ["think", "reason", "reasoning", "thought", "Thought"]
  1012. code_interpreter_tags = ["oi::code_interpreter"]
  1013. try:
  1014. for event in events:
  1015. await event_emitter(
  1016. {
  1017. "type": "chat:completion",
  1018. "data": event,
  1019. }
  1020. )
  1021. # Save message in the database
  1022. Chats.upsert_message_to_chat_by_id_and_message_id(
  1023. metadata["chat_id"],
  1024. metadata["message_id"],
  1025. {
  1026. **event,
  1027. },
  1028. )
  1029. async def stream_body_handler(response):
  1030. nonlocal content
  1031. nonlocal content_blocks
  1032. async for line in response.body_iterator:
  1033. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1034. data = line
  1035. # Skip empty lines
  1036. if not data.strip():
  1037. continue
  1038. # "data:" is the prefix for each event
  1039. if not data.startswith("data:"):
  1040. continue
  1041. # Remove the prefix
  1042. data = data[len("data:") :].strip()
  1043. try:
  1044. data = json.loads(data)
  1045. if "selected_model_id" in data:
  1046. model_id = data["selected_model_id"]
  1047. Chats.upsert_message_to_chat_by_id_and_message_id(
  1048. metadata["chat_id"],
  1049. metadata["message_id"],
  1050. {
  1051. "selectedModelId": model_id,
  1052. },
  1053. )
  1054. else:
  1055. choices = data.get("choices", [])
  1056. if not choices:
  1057. continue
  1058. value = choices[0].get("delta", {}).get("content")
  1059. if value:
  1060. content = f"{content}{value}"
  1061. content_blocks[-1]["content"] = (
  1062. content_blocks[-1]["content"] + value
  1063. )
  1064. if DETECT_REASONING:
  1065. content, content_blocks = tag_content_handler(
  1066. "reasoning",
  1067. reasoning_tags,
  1068. content,
  1069. content_blocks,
  1070. )
  1071. if DETECT_CODE_INTERPRETER:
  1072. content, content_blocks = tag_content_handler(
  1073. "code_interpreter",
  1074. code_interpreter_tags,
  1075. content,
  1076. content_blocks,
  1077. )
  1078. if ENABLE_REALTIME_CHAT_SAVE:
  1079. # Save message in the database
  1080. Chats.upsert_message_to_chat_by_id_and_message_id(
  1081. metadata["chat_id"],
  1082. metadata["message_id"],
  1083. {
  1084. "content": serialize_content_blocks(
  1085. content_blocks
  1086. ),
  1087. },
  1088. )
  1089. else:
  1090. data = {
  1091. "content": serialize_content_blocks(
  1092. content_blocks
  1093. ),
  1094. }
  1095. await event_emitter(
  1096. {
  1097. "type": "chat:completion",
  1098. "data": data,
  1099. }
  1100. )
  1101. except Exception as e:
  1102. done = "data: [DONE]" in line
  1103. if done:
  1104. # Clean up the last text block
  1105. if content_blocks[-1]["type"] == "text":
  1106. content_blocks[-1]["content"] = content_blocks[-1][
  1107. "content"
  1108. ].strip()
  1109. if not content_blocks[-1]["content"]:
  1110. content_blocks.pop()
  1111. pass
  1112. else:
  1113. log.debug("Error: ", e)
  1114. continue
  1115. if response.background:
  1116. await response.background()
  1117. await stream_body_handler(response)
  1118. MAX_RETRIES = 5
  1119. retries = 0
  1120. while (
  1121. content_blocks[-1]["type"] == "code_interpreter"
  1122. and retries < MAX_RETRIES
  1123. ):
  1124. retries += 1
  1125. try:
  1126. if content_blocks[-1]["attributes"].get("type") == "code":
  1127. output = await event_caller(
  1128. {
  1129. "type": "execute:pyodide",
  1130. "data": {
  1131. "id": str(uuid4()),
  1132. "code": content_blocks[-1]["content"],
  1133. },
  1134. }
  1135. )
  1136. except Exception as e:
  1137. output = str(e)
  1138. content_blocks.append(
  1139. {
  1140. "type": "code_interpreter",
  1141. "attributes": {
  1142. "type": "output",
  1143. },
  1144. "content": output,
  1145. }
  1146. )
  1147. content_blocks.append(
  1148. {
  1149. "type": "text",
  1150. "content": "",
  1151. }
  1152. )
  1153. try:
  1154. res = await generate_chat_completion(
  1155. request,
  1156. {
  1157. "model": model_id,
  1158. "stream": True,
  1159. "messages": [
  1160. *form_data["messages"],
  1161. {
  1162. "role": "assistant",
  1163. "content": serialize_content_blocks(
  1164. content_blocks
  1165. ),
  1166. },
  1167. ],
  1168. },
  1169. user,
  1170. )
  1171. if isinstance(res, StreamingResponse):
  1172. await stream_body_handler(res)
  1173. else:
  1174. break
  1175. except Exception as e:
  1176. log.debug(e)
  1177. break
  1178. await event_emitter(
  1179. {
  1180. "type": "chat:completion",
  1181. "data": {
  1182. "content": serialize_content_blocks(content_blocks),
  1183. },
  1184. }
  1185. )
  1186. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1187. data = {
  1188. "done": True,
  1189. "content": serialize_content_blocks(content_blocks),
  1190. "title": title,
  1191. }
  1192. if not ENABLE_REALTIME_CHAT_SAVE:
  1193. # Save message in the database
  1194. Chats.upsert_message_to_chat_by_id_and_message_id(
  1195. metadata["chat_id"],
  1196. metadata["message_id"],
  1197. {
  1198. "content": serialize_content_blocks(content_blocks),
  1199. },
  1200. )
  1201. # Send a webhook notification if the user is not active
  1202. if get_active_status_by_user_id(user.id) is None:
  1203. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1204. if webhook_url:
  1205. post_webhook(
  1206. webhook_url,
  1207. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1208. {
  1209. "action": "chat",
  1210. "message": content,
  1211. "title": title,
  1212. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1213. },
  1214. )
  1215. await event_emitter(
  1216. {
  1217. "type": "chat:completion",
  1218. "data": data,
  1219. }
  1220. )
  1221. await background_tasks_handler()
  1222. except asyncio.CancelledError:
  1223. print("Task was cancelled!")
  1224. await event_emitter({"type": "task-cancelled"})
  1225. if not ENABLE_REALTIME_CHAT_SAVE:
  1226. # Save message in the database
  1227. Chats.upsert_message_to_chat_by_id_and_message_id(
  1228. metadata["chat_id"],
  1229. metadata["message_id"],
  1230. {
  1231. "content": content,
  1232. },
  1233. )
  1234. if response.background is not None:
  1235. await response.background()
  1236. # background_tasks.add_task(post_response_handler, response, events)
  1237. task_id, _ = create_task(post_response_handler(response, events))
  1238. return {"status": True, "task_id": task_id}
  1239. else:
  1240. # Fallback to the original response
  1241. async def stream_wrapper(original_generator, events):
  1242. def wrap_item(item):
  1243. return f"data: {item}\n\n"
  1244. for event in events:
  1245. yield wrap_item(json.dumps(event))
  1246. async for data in original_generator:
  1247. yield data
  1248. return StreamingResponse(
  1249. stream_wrapper(response.body_iterator, events),
  1250. headers=dict(response.headers),
  1251. background=response.background,
  1252. )