middleware.py 55 KB

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