middleware.py 54 KB

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