middleware.py 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404
  1. import time
  2. import logging
  3. import sys
  4. import os
  5. import base64
  6. import asyncio
  7. from aiocache import cached
  8. from typing import Any, Optional
  9. import random
  10. import json
  11. import html
  12. import inspect
  13. import re
  14. import ast
  15. from uuid import uuid4
  16. from concurrent.futures import ThreadPoolExecutor
  17. from fastapi import Request, HTTPException
  18. from starlette.responses import Response, StreamingResponse
  19. from open_webui.models.chats import Chats
  20. from open_webui.models.users import Users
  21. from open_webui.socket.main import (
  22. get_event_call,
  23. get_event_emitter,
  24. get_active_status_by_user_id,
  25. )
  26. from open_webui.routers.tasks import (
  27. generate_queries,
  28. generate_title,
  29. generate_image_prompt,
  30. generate_chat_tags,
  31. )
  32. from open_webui.routers.retrieval import process_web_search, SearchForm
  33. from open_webui.routers.images import image_generations, GenerateImageForm
  34. from open_webui.routers.pipelines import (
  35. process_pipeline_inlet_filter,
  36. process_pipeline_outlet_filter,
  37. )
  38. from open_webui.routers.memories import query_memory, QueryMemoryForm
  39. from open_webui.utils.webhook import post_webhook
  40. from open_webui.models.users import UserModel
  41. from open_webui.models.functions import Functions
  42. from open_webui.models.models import Models
  43. from open_webui.retrieval.utils import get_sources_from_files
  44. from open_webui.utils.chat import generate_chat_completion
  45. from open_webui.utils.task import (
  46. get_task_model_id,
  47. rag_template,
  48. tools_function_calling_generation_template,
  49. )
  50. from open_webui.utils.misc import (
  51. deep_update,
  52. get_message_list,
  53. add_or_update_system_message,
  54. add_or_update_user_message,
  55. get_last_user_message,
  56. get_last_assistant_message,
  57. prepend_to_first_user_message_content,
  58. convert_logit_bias_input_to_json,
  59. )
  60. from open_webui.utils.tools import get_tools
  61. from open_webui.utils.plugin import load_function_module_by_id
  62. from open_webui.utils.filter import (
  63. get_sorted_filter_ids,
  64. process_filter_functions,
  65. )
  66. from open_webui.utils.code_interpreter import execute_code_jupyter
  67. from open_webui.tasks import create_task
  68. from open_webui.config import (
  69. CACHE_DIR,
  70. DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  71. DEFAULT_CODE_INTERPRETER_PROMPT,
  72. )
  73. from open_webui.env import (
  74. SRC_LOG_LEVELS,
  75. GLOBAL_LOG_LEVEL,
  76. BYPASS_MODEL_ACCESS_CONTROL,
  77. ENABLE_REALTIME_CHAT_SAVE,
  78. )
  79. from open_webui.constants import TASKS
  80. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  81. log = logging.getLogger(__name__)
  82. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  83. async def chat_completion_tools_handler(
  84. request: Request, body: dict, extra_params: dict, user: UserModel, models, tools
  85. ) -> tuple[dict, dict]:
  86. async def get_content_from_response(response) -> Optional[str]:
  87. content = None
  88. if hasattr(response, "body_iterator"):
  89. async for chunk in response.body_iterator:
  90. data = json.loads(chunk.decode("utf-8"))
  91. content = data["choices"][0]["message"]["content"]
  92. # Cleanup any remaining background tasks if necessary
  93. if response.background is not None:
  94. await response.background()
  95. else:
  96. content = response["choices"][0]["message"]["content"]
  97. return content
  98. def get_tools_function_calling_payload(messages, task_model_id, content):
  99. user_message = get_last_user_message(messages)
  100. history = "\n".join(
  101. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  102. for message in messages[::-1][:4]
  103. )
  104. prompt = f"History:\n{history}\nQuery: {user_message}"
  105. return {
  106. "model": task_model_id,
  107. "messages": [
  108. {"role": "system", "content": content},
  109. {"role": "user", "content": f"Query: {prompt}"},
  110. ],
  111. "stream": False,
  112. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  113. }
  114. event_caller = extra_params["__event_call__"]
  115. metadata = extra_params["__metadata__"]
  116. task_model_id = get_task_model_id(
  117. body["model"],
  118. request.app.state.config.TASK_MODEL,
  119. request.app.state.config.TASK_MODEL_EXTERNAL,
  120. models,
  121. )
  122. skip_files = False
  123. sources = []
  124. specs = [tool["spec"] for tool in tools.values()]
  125. tools_specs = json.dumps(specs)
  126. if request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  127. template = request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  128. else:
  129. template = DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  130. tools_function_calling_prompt = tools_function_calling_generation_template(
  131. template, tools_specs
  132. )
  133. payload = get_tools_function_calling_payload(
  134. body["messages"], task_model_id, tools_function_calling_prompt
  135. )
  136. try:
  137. response = await generate_chat_completion(request, form_data=payload, user=user)
  138. log.debug(f"{response=}")
  139. content = await get_content_from_response(response)
  140. log.debug(f"{content=}")
  141. if not content:
  142. return body, {}
  143. try:
  144. content = content[content.find("{") : content.rfind("}") + 1]
  145. if not content:
  146. raise Exception("No JSON object found in the response")
  147. result = json.loads(content)
  148. async def tool_call_handler(tool_call):
  149. nonlocal skip_files
  150. log.debug(f"{tool_call=}")
  151. tool_function_name = tool_call.get("name", None)
  152. if tool_function_name not in tools:
  153. return body, {}
  154. tool_function_params = tool_call.get("parameters", {})
  155. try:
  156. tool = tools[tool_function_name]
  157. spec = tool.get("spec", {})
  158. allowed_params = (
  159. spec.get("parameters", {}).get("properties", {}).keys()
  160. )
  161. tool_function_params = {
  162. k: v
  163. for k, v in tool_function_params.items()
  164. if k in allowed_params
  165. }
  166. if tool.get("direct", False):
  167. tool_result = await event_caller(
  168. {
  169. "type": "execute:tool",
  170. "data": {
  171. "id": str(uuid4()),
  172. "name": tool_function_name,
  173. "params": tool_function_params,
  174. "server": tool.get("server", {}),
  175. "session_id": metadata.get("session_id", None),
  176. },
  177. }
  178. )
  179. else:
  180. tool_function = tool["callable"]
  181. tool_result = await tool_function(**tool_function_params)
  182. except Exception as e:
  183. tool_result = str(e)
  184. tool_result_files = []
  185. if isinstance(tool_result, list):
  186. for item in tool_result:
  187. # check if string
  188. if isinstance(item, str) and item.startswith("data:"):
  189. tool_result_files.append(item)
  190. tool_result.remove(item)
  191. if isinstance(tool_result, dict) or isinstance(tool_result, list):
  192. tool_result = json.dumps(tool_result, indent=2)
  193. if isinstance(tool_result, str):
  194. tool = tools[tool_function_name]
  195. tool_id = tool.get("tool_id", "")
  196. tool_name = (
  197. f"{tool_id}/{tool_function_name}"
  198. if tool_id
  199. else f"{tool_function_name}"
  200. )
  201. if tool.get("metadata", {}).get("citation", False) or tool.get(
  202. "direct", False
  203. ):
  204. # Citation is enabled for this tool
  205. sources.append(
  206. {
  207. "source": {
  208. "name": (f"TOOL:{tool_name}"),
  209. },
  210. "document": [tool_result],
  211. "metadata": [
  212. {
  213. "source": (f"TOOL:{tool_name}"),
  214. "parameters": tool_function_params,
  215. }
  216. ],
  217. }
  218. )
  219. else:
  220. # Citation is not enabled for this tool
  221. body["messages"] = add_or_update_user_message(
  222. f"\nTool `{tool_name}` Output: {tool_result}",
  223. body["messages"],
  224. )
  225. if (
  226. tools[tool_function_name]
  227. .get("metadata", {})
  228. .get("file_handler", False)
  229. ):
  230. skip_files = True
  231. # check if "tool_calls" in result
  232. if result.get("tool_calls"):
  233. for tool_call in result.get("tool_calls"):
  234. await tool_call_handler(tool_call)
  235. else:
  236. await tool_call_handler(result)
  237. except Exception as e:
  238. log.debug(f"Error: {e}")
  239. content = None
  240. except Exception as e:
  241. log.debug(f"Error: {e}")
  242. content = None
  243. log.debug(f"tool_contexts: {sources}")
  244. if skip_files and "files" in body.get("metadata", {}):
  245. del body["metadata"]["files"]
  246. return body, {"sources": sources}
  247. async def chat_memory_handler(
  248. request: Request, form_data: dict, extra_params: dict, user
  249. ):
  250. results = await query_memory(
  251. request,
  252. QueryMemoryForm(
  253. **{"content": get_last_user_message(form_data["messages"]), "k": 3}
  254. ),
  255. user,
  256. )
  257. user_context = ""
  258. if results and hasattr(results, "documents"):
  259. if results.documents and len(results.documents) > 0:
  260. for doc_idx, doc in enumerate(results.documents[0]):
  261. created_at_date = "Unknown Date"
  262. if results.metadatas[0][doc_idx].get("created_at"):
  263. created_at_timestamp = results.metadatas[0][doc_idx]["created_at"]
  264. created_at_date = time.strftime(
  265. "%Y-%m-%d", time.localtime(created_at_timestamp)
  266. )
  267. user_context += f"{doc_idx + 1}. [{created_at_date}] {doc}\n"
  268. form_data["messages"] = add_or_update_system_message(
  269. f"User Context:\n{user_context}\n", form_data["messages"], append=True
  270. )
  271. return form_data
  272. async def chat_web_search_handler(
  273. request: Request, form_data: dict, extra_params: dict, user
  274. ):
  275. event_emitter = extra_params["__event_emitter__"]
  276. await event_emitter(
  277. {
  278. "type": "status",
  279. "data": {
  280. "action": "web_search",
  281. "description": "Generating search query",
  282. "done": False,
  283. },
  284. }
  285. )
  286. messages = form_data["messages"]
  287. user_message = get_last_user_message(messages)
  288. queries = []
  289. try:
  290. res = await generate_queries(
  291. request,
  292. {
  293. "model": form_data["model"],
  294. "messages": messages,
  295. "prompt": user_message,
  296. "type": "web_search",
  297. },
  298. user,
  299. )
  300. response = res["choices"][0]["message"]["content"]
  301. try:
  302. bracket_start = response.find("{")
  303. bracket_end = response.rfind("}") + 1
  304. if bracket_start == -1 or bracket_end == -1:
  305. raise Exception("No JSON object found in the response")
  306. response = response[bracket_start:bracket_end]
  307. queries = json.loads(response)
  308. queries = queries.get("queries", [])
  309. except Exception as e:
  310. queries = [response]
  311. except Exception as e:
  312. log.exception(e)
  313. queries = [user_message]
  314. # Check if generated queries are empty
  315. if len(queries) == 1 and queries[0].strip() == "":
  316. queries = [user_message]
  317. # Check if queries are not found
  318. if len(queries) == 0:
  319. await event_emitter(
  320. {
  321. "type": "status",
  322. "data": {
  323. "action": "web_search",
  324. "description": "No search query generated",
  325. "done": True,
  326. },
  327. }
  328. )
  329. return form_data
  330. await event_emitter(
  331. {
  332. "type": "status",
  333. "data": {
  334. "action": "web_search",
  335. "description": "Searching the web",
  336. "done": False,
  337. },
  338. }
  339. )
  340. try:
  341. results = await process_web_search(
  342. request,
  343. SearchForm(queries=queries),
  344. user=user,
  345. )
  346. if results:
  347. files = form_data.get("files", [])
  348. if results.get("collection_names"):
  349. for col_idx, collection_name in enumerate(
  350. results.get("collection_names")
  351. ):
  352. files.append(
  353. {
  354. "collection_name": collection_name,
  355. "name": ", ".join(queries),
  356. "type": "web_search",
  357. "urls": results["filenames"],
  358. "queries": queries,
  359. }
  360. )
  361. elif results.get("docs"):
  362. # Invoked when bypass embedding and retrieval is set to True
  363. docs = results["docs"]
  364. files.append(
  365. {
  366. "docs": docs,
  367. "name": ", ".join(queries),
  368. "type": "web_search",
  369. "urls": results["filenames"],
  370. "queries": queries,
  371. }
  372. )
  373. form_data["files"] = files
  374. await event_emitter(
  375. {
  376. "type": "status",
  377. "data": {
  378. "action": "web_search",
  379. "description": "Searched {{count}} sites",
  380. "urls": results["filenames"],
  381. "done": True,
  382. },
  383. }
  384. )
  385. else:
  386. await event_emitter(
  387. {
  388. "type": "status",
  389. "data": {
  390. "action": "web_search",
  391. "description": "No search results found",
  392. "done": True,
  393. "error": True,
  394. },
  395. }
  396. )
  397. except Exception as e:
  398. log.exception(e)
  399. await event_emitter(
  400. {
  401. "type": "status",
  402. "data": {
  403. "action": "web_search",
  404. "description": "An error occurred while searching the web",
  405. "queries": queries,
  406. "done": True,
  407. "error": True,
  408. },
  409. }
  410. )
  411. return form_data
  412. async def chat_image_generation_handler(
  413. request: Request, form_data: dict, extra_params: dict, user
  414. ):
  415. __event_emitter__ = extra_params["__event_emitter__"]
  416. await __event_emitter__(
  417. {
  418. "type": "status",
  419. "data": {"description": "Generating an image", "done": False},
  420. }
  421. )
  422. messages = form_data["messages"]
  423. user_message = get_last_user_message(messages)
  424. prompt = user_message
  425. negative_prompt = ""
  426. if request.app.state.config.ENABLE_IMAGE_PROMPT_GENERATION:
  427. try:
  428. res = await generate_image_prompt(
  429. request,
  430. {
  431. "model": form_data["model"],
  432. "messages": messages,
  433. },
  434. user,
  435. )
  436. response = res["choices"][0]["message"]["content"]
  437. try:
  438. bracket_start = response.find("{")
  439. bracket_end = response.rfind("}") + 1
  440. if bracket_start == -1 or bracket_end == -1:
  441. raise Exception("No JSON object found in the response")
  442. response = response[bracket_start:bracket_end]
  443. response = json.loads(response)
  444. prompt = response.get("prompt", [])
  445. except Exception as e:
  446. prompt = user_message
  447. except Exception as e:
  448. log.exception(e)
  449. prompt = user_message
  450. system_message_content = ""
  451. try:
  452. images = await image_generations(
  453. request=request,
  454. form_data=GenerateImageForm(**{"prompt": prompt}),
  455. user=user,
  456. )
  457. await __event_emitter__(
  458. {
  459. "type": "status",
  460. "data": {"description": "Generated an image", "done": True},
  461. }
  462. )
  463. await __event_emitter__(
  464. {
  465. "type": "files",
  466. "data": {
  467. "files": [
  468. {
  469. "type": "image",
  470. "url": image["url"],
  471. }
  472. for image in images
  473. ]
  474. },
  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 occurred 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 occurred</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. queries = []
  501. try:
  502. queries_response = await generate_queries(
  503. request,
  504. {
  505. "model": body["model"],
  506. "messages": body["messages"],
  507. "type": "retrieval",
  508. },
  509. user,
  510. )
  511. queries_response = queries_response["choices"][0]["message"]["content"]
  512. try:
  513. bracket_start = queries_response.find("{")
  514. bracket_end = queries_response.rfind("}") + 1
  515. if bracket_start == -1 or bracket_end == -1:
  516. raise Exception("No JSON object found in the response")
  517. queries_response = queries_response[bracket_start:bracket_end]
  518. queries_response = json.loads(queries_response)
  519. except Exception as e:
  520. queries_response = {"queries": [queries_response]}
  521. queries = queries_response.get("queries", [])
  522. except:
  523. pass
  524. if len(queries) == 0:
  525. queries = [get_last_user_message(body["messages"])]
  526. try:
  527. # Offload get_sources_from_files to a separate thread
  528. loop = asyncio.get_running_loop()
  529. with ThreadPoolExecutor() as executor:
  530. sources = await loop.run_in_executor(
  531. executor,
  532. lambda: get_sources_from_files(
  533. request=request,
  534. files=files,
  535. queries=queries,
  536. embedding_function=lambda query, prefix: request.app.state.EMBEDDING_FUNCTION(
  537. query, prefix=prefix, user=user
  538. ),
  539. k=request.app.state.config.TOP_K,
  540. reranking_function=request.app.state.rf,
  541. k_reranker=request.app.state.config.TOP_K_RERANKER,
  542. r=request.app.state.config.RELEVANCE_THRESHOLD,
  543. hybrid_bm25_weight=request.app.state.config.HYBRID_BM25_WEIGHT,
  544. hybrid_search=request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  545. full_context=request.app.state.config.RAG_FULL_CONTEXT,
  546. ),
  547. )
  548. except Exception as e:
  549. log.exception(e)
  550. log.debug(f"rag_contexts:sources: {sources}")
  551. return body, {"sources": sources}
  552. def apply_params_to_form_data(form_data, model):
  553. params = form_data.pop("params", {})
  554. custom_params = params.pop("custom_params", {})
  555. if custom_params:
  556. # If custom_params are provided, merge them into params
  557. params = deep_update(params, custom_params)
  558. if model.get("ollama"):
  559. form_data["options"] = params
  560. if "format" in params:
  561. form_data["format"] = params["format"]
  562. if "keep_alive" in params:
  563. form_data["keep_alive"] = params["keep_alive"]
  564. else:
  565. if isinstance(params, dict):
  566. for key, value in params.items():
  567. if value is not None:
  568. form_data[key] = value
  569. if "logit_bias" in params and params["logit_bias"] is not None:
  570. try:
  571. form_data["logit_bias"] = json.loads(
  572. convert_logit_bias_input_to_json(params["logit_bias"])
  573. )
  574. except Exception as e:
  575. log.exception(f"Error parsing logit_bias: {e}")
  576. return form_data
  577. async def process_chat_payload(request, form_data, user, metadata, model):
  578. form_data = apply_params_to_form_data(form_data, model)
  579. log.debug(f"form_data: {form_data}")
  580. event_emitter = get_event_emitter(metadata)
  581. event_call = get_event_call(metadata)
  582. extra_params = {
  583. "__event_emitter__": event_emitter,
  584. "__event_call__": event_call,
  585. "__user__": {
  586. "id": user.id,
  587. "email": user.email,
  588. "name": user.name,
  589. "role": user.role,
  590. },
  591. "__metadata__": metadata,
  592. "__request__": request,
  593. "__model__": model,
  594. }
  595. # Initialize events to store additional event to be sent to the client
  596. # Initialize contexts and citation
  597. if getattr(request.state, "direct", False) and hasattr(request.state, "model"):
  598. models = {
  599. request.state.model["id"]: request.state.model,
  600. }
  601. else:
  602. models = request.app.state.MODELS
  603. task_model_id = get_task_model_id(
  604. form_data["model"],
  605. request.app.state.config.TASK_MODEL,
  606. request.app.state.config.TASK_MODEL_EXTERNAL,
  607. models,
  608. )
  609. events = []
  610. sources = []
  611. user_message = get_last_user_message(form_data["messages"])
  612. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  613. if model_knowledge:
  614. await event_emitter(
  615. {
  616. "type": "status",
  617. "data": {
  618. "action": "knowledge_search",
  619. "query": user_message,
  620. "done": False,
  621. },
  622. }
  623. )
  624. knowledge_files = []
  625. for item in model_knowledge:
  626. if item.get("collection_name"):
  627. knowledge_files.append(
  628. {
  629. "id": item.get("collection_name"),
  630. "name": item.get("name"),
  631. "legacy": True,
  632. }
  633. )
  634. elif item.get("collection_names"):
  635. knowledge_files.append(
  636. {
  637. "name": item.get("name"),
  638. "type": "collection",
  639. "collection_names": item.get("collection_names"),
  640. "legacy": True,
  641. }
  642. )
  643. else:
  644. knowledge_files.append(item)
  645. files = form_data.get("files", [])
  646. files.extend(knowledge_files)
  647. form_data["files"] = files
  648. variables = form_data.pop("variables", None)
  649. # Process the form_data through the pipeline
  650. try:
  651. form_data = await process_pipeline_inlet_filter(
  652. request, form_data, user, models
  653. )
  654. except Exception as e:
  655. raise e
  656. try:
  657. filter_functions = [
  658. Functions.get_function_by_id(filter_id)
  659. for filter_id in get_sorted_filter_ids(
  660. request, model, metadata.get("filter_ids", [])
  661. )
  662. ]
  663. form_data, flags = await process_filter_functions(
  664. request=request,
  665. filter_functions=filter_functions,
  666. filter_type="inlet",
  667. form_data=form_data,
  668. extra_params=extra_params,
  669. )
  670. except Exception as e:
  671. raise Exception(f"Error: {e}")
  672. features = form_data.pop("features", None)
  673. if features:
  674. if "memory" in features and features["memory"]:
  675. form_data = await chat_memory_handler(
  676. request, form_data, extra_params, user
  677. )
  678. if "web_search" in features and features["web_search"]:
  679. form_data = await chat_web_search_handler(
  680. request, form_data, extra_params, user
  681. )
  682. if "image_generation" in features and features["image_generation"]:
  683. form_data = await chat_image_generation_handler(
  684. request, form_data, extra_params, user
  685. )
  686. if "code_interpreter" in features and features["code_interpreter"]:
  687. form_data["messages"] = add_or_update_user_message(
  688. (
  689. request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE
  690. if request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE != ""
  691. else DEFAULT_CODE_INTERPRETER_PROMPT
  692. ),
  693. form_data["messages"],
  694. )
  695. tool_ids = form_data.pop("tool_ids", None)
  696. files = form_data.pop("files", None)
  697. # Remove files duplicates
  698. if files:
  699. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  700. metadata = {
  701. **metadata,
  702. "tool_ids": tool_ids,
  703. "files": files,
  704. }
  705. form_data["metadata"] = metadata
  706. # Server side tools
  707. tool_ids = metadata.get("tool_ids", None)
  708. # Client side tools
  709. tool_servers = metadata.get("tool_servers", None)
  710. log.debug(f"{tool_ids=}")
  711. log.debug(f"{tool_servers=}")
  712. tools_dict = {}
  713. if tool_ids:
  714. tools_dict = get_tools(
  715. request,
  716. tool_ids,
  717. user,
  718. {
  719. **extra_params,
  720. "__model__": models[task_model_id],
  721. "__messages__": form_data["messages"],
  722. "__files__": metadata.get("files", []),
  723. },
  724. )
  725. if tool_servers:
  726. for tool_server in tool_servers:
  727. tool_specs = tool_server.pop("specs", [])
  728. for tool in tool_specs:
  729. tools_dict[tool["name"]] = {
  730. "spec": tool,
  731. "direct": True,
  732. "server": tool_server,
  733. }
  734. if tools_dict:
  735. if metadata.get("function_calling") == "native":
  736. # If the function calling is native, then call the tools function calling handler
  737. metadata["tools"] = tools_dict
  738. form_data["tools"] = [
  739. {"type": "function", "function": tool.get("spec", {})}
  740. for tool in tools_dict.values()
  741. ]
  742. else:
  743. # If the function calling is not native, then call the tools function calling handler
  744. try:
  745. form_data, flags = await chat_completion_tools_handler(
  746. request, form_data, extra_params, user, models, tools_dict
  747. )
  748. sources.extend(flags.get("sources", []))
  749. except Exception as e:
  750. log.exception(e)
  751. try:
  752. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  753. sources.extend(flags.get("sources", []))
  754. except Exception as e:
  755. log.exception(e)
  756. # If context is not empty, insert it into the messages
  757. if len(sources) > 0:
  758. context_string = ""
  759. citation_idx = {}
  760. for source in sources:
  761. if "document" in source:
  762. for doc_context, doc_meta in zip(
  763. source["document"], source["metadata"]
  764. ):
  765. source_name = source.get("source", {}).get("name", None)
  766. citation_id = (
  767. doc_meta.get("source", None)
  768. or source.get("source", {}).get("id", None)
  769. or "N/A"
  770. )
  771. if citation_id not in citation_idx:
  772. citation_idx[citation_id] = len(citation_idx) + 1
  773. context_string += (
  774. f'<source id="{citation_idx[citation_id]}"'
  775. + (f' name="{source_name}"' if source_name else "")
  776. + f">{doc_context}</source>\n"
  777. )
  778. context_string = context_string.strip()
  779. prompt = get_last_user_message(form_data["messages"])
  780. if prompt is None:
  781. raise Exception("No user message found")
  782. if (
  783. request.app.state.config.RELEVANCE_THRESHOLD == 0
  784. and context_string.strip() == ""
  785. ):
  786. log.debug(
  787. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  788. )
  789. # Workaround for Ollama 2.0+ system prompt issue
  790. # TODO: replace with add_or_update_system_message
  791. if model.get("owned_by") == "ollama":
  792. form_data["messages"] = prepend_to_first_user_message_content(
  793. rag_template(
  794. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  795. ),
  796. form_data["messages"],
  797. )
  798. else:
  799. form_data["messages"] = add_or_update_system_message(
  800. rag_template(
  801. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  802. ),
  803. form_data["messages"],
  804. )
  805. # If there are citations, add them to the data_items
  806. sources = [
  807. source
  808. for source in sources
  809. if source.get("source", {}).get("name", "")
  810. or source.get("source", {}).get("id", "")
  811. ]
  812. if len(sources) > 0:
  813. events.append({"sources": sources})
  814. if model_knowledge:
  815. await event_emitter(
  816. {
  817. "type": "status",
  818. "data": {
  819. "action": "knowledge_search",
  820. "query": user_message,
  821. "done": True,
  822. "hidden": True,
  823. },
  824. }
  825. )
  826. return form_data, metadata, events
  827. async def process_chat_response(
  828. request, response, form_data, user, metadata, model, events, tasks
  829. ):
  830. async def background_tasks_handler():
  831. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  832. message = message_map.get(metadata["message_id"]) if message_map else None
  833. if message:
  834. message_list = get_message_list(message_map, metadata["message_id"])
  835. # Remove details tags and files from the messages.
  836. # as get_message_list creates a new list, it does not affect
  837. # the original messages outside of this handler
  838. messages = []
  839. for message in message_list:
  840. content = message.get("content", "")
  841. if isinstance(content, list):
  842. for item in content:
  843. if item.get("type") == "text":
  844. content = item["text"]
  845. break
  846. if isinstance(content, str):
  847. content = re.sub(
  848. r"<details\b[^>]*>.*?<\/details>|!\[.*?\]\(.*?\)",
  849. "",
  850. content,
  851. flags=re.S | re.I,
  852. ).strip()
  853. messages.append(
  854. {
  855. **message,
  856. "role": message.get(
  857. "role", "assistant"
  858. ), # Safe fallback for missing role
  859. "content": content,
  860. }
  861. )
  862. if tasks and messages:
  863. if TASKS.TITLE_GENERATION in tasks:
  864. if tasks[TASKS.TITLE_GENERATION]:
  865. res = await generate_title(
  866. request,
  867. {
  868. "model": message["model"],
  869. "messages": messages,
  870. "chat_id": metadata["chat_id"],
  871. },
  872. user,
  873. )
  874. if res and isinstance(res, dict):
  875. if len(res.get("choices", [])) == 1:
  876. title_string = (
  877. res.get("choices", [])[0]
  878. .get("message", {})
  879. .get("content", message.get("content", "New Chat"))
  880. )
  881. else:
  882. title_string = ""
  883. title_string = title_string[
  884. title_string.find("{") : title_string.rfind("}") + 1
  885. ]
  886. try:
  887. title = json.loads(title_string).get(
  888. "title", "New Chat"
  889. )
  890. except Exception as e:
  891. title = ""
  892. if not title:
  893. title = messages[0].get("content", "New Chat")
  894. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  895. await event_emitter(
  896. {
  897. "type": "chat:title",
  898. "data": title,
  899. }
  900. )
  901. elif len(messages) == 2:
  902. title = messages[0].get("content", "New Chat")
  903. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  904. await event_emitter(
  905. {
  906. "type": "chat:title",
  907. "data": message.get("content", "New Chat"),
  908. }
  909. )
  910. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  911. res = await generate_chat_tags(
  912. request,
  913. {
  914. "model": message["model"],
  915. "messages": messages,
  916. "chat_id": metadata["chat_id"],
  917. },
  918. user,
  919. )
  920. if res and isinstance(res, dict):
  921. if len(res.get("choices", [])) == 1:
  922. tags_string = (
  923. res.get("choices", [])[0]
  924. .get("message", {})
  925. .get("content", "")
  926. )
  927. else:
  928. tags_string = ""
  929. tags_string = tags_string[
  930. tags_string.find("{") : tags_string.rfind("}") + 1
  931. ]
  932. try:
  933. tags = json.loads(tags_string).get("tags", [])
  934. Chats.update_chat_tags_by_id(
  935. metadata["chat_id"], tags, user
  936. )
  937. await event_emitter(
  938. {
  939. "type": "chat:tags",
  940. "data": tags,
  941. }
  942. )
  943. except Exception as e:
  944. pass
  945. event_emitter = None
  946. event_caller = None
  947. if (
  948. "session_id" in metadata
  949. and metadata["session_id"]
  950. and "chat_id" in metadata
  951. and metadata["chat_id"]
  952. and "message_id" in metadata
  953. and metadata["message_id"]
  954. ):
  955. event_emitter = get_event_emitter(metadata)
  956. event_caller = get_event_call(metadata)
  957. # Non-streaming response
  958. if not isinstance(response, StreamingResponse):
  959. if event_emitter:
  960. if "error" in response:
  961. error = response["error"].get("detail", response["error"])
  962. Chats.upsert_message_to_chat_by_id_and_message_id(
  963. metadata["chat_id"],
  964. metadata["message_id"],
  965. {
  966. "error": {"content": error},
  967. },
  968. )
  969. if "selected_model_id" in response:
  970. Chats.upsert_message_to_chat_by_id_and_message_id(
  971. metadata["chat_id"],
  972. metadata["message_id"],
  973. {
  974. "selectedModelId": response["selected_model_id"],
  975. },
  976. )
  977. choices = response.get("choices", [])
  978. if choices and choices[0].get("message", {}).get("content"):
  979. content = response["choices"][0]["message"]["content"]
  980. if content:
  981. await event_emitter(
  982. {
  983. "type": "chat:completion",
  984. "data": response,
  985. }
  986. )
  987. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  988. await event_emitter(
  989. {
  990. "type": "chat:completion",
  991. "data": {
  992. "done": True,
  993. "content": content,
  994. "title": title,
  995. },
  996. }
  997. )
  998. # Save message in the database
  999. Chats.upsert_message_to_chat_by_id_and_message_id(
  1000. metadata["chat_id"],
  1001. metadata["message_id"],
  1002. {
  1003. "role": "assistant",
  1004. "content": content,
  1005. },
  1006. )
  1007. # Send a webhook notification if the user is not active
  1008. if not get_active_status_by_user_id(user.id):
  1009. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1010. if webhook_url:
  1011. post_webhook(
  1012. request.app.state.WEBUI_NAME,
  1013. webhook_url,
  1014. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1015. {
  1016. "action": "chat",
  1017. "message": content,
  1018. "title": title,
  1019. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1020. },
  1021. )
  1022. await background_tasks_handler()
  1023. if events and isinstance(events, list) and isinstance(response, dict):
  1024. extra_response = {}
  1025. for event in events:
  1026. if isinstance(event, dict):
  1027. extra_response.update(event)
  1028. else:
  1029. extra_response[event] = True
  1030. response = {
  1031. **extra_response,
  1032. **response,
  1033. }
  1034. return response
  1035. else:
  1036. if events and isinstance(events, list) and isinstance(response, dict):
  1037. extra_response = {}
  1038. for event in events:
  1039. if isinstance(event, dict):
  1040. extra_response.update(event)
  1041. else:
  1042. extra_response[event] = True
  1043. response = {
  1044. **extra_response,
  1045. **response,
  1046. }
  1047. return response
  1048. # Non standard response
  1049. if not any(
  1050. content_type in response.headers["Content-Type"]
  1051. for content_type in ["text/event-stream", "application/x-ndjson"]
  1052. ):
  1053. return response
  1054. extra_params = {
  1055. "__event_emitter__": event_emitter,
  1056. "__event_call__": event_caller,
  1057. "__user__": {
  1058. "id": user.id,
  1059. "email": user.email,
  1060. "name": user.name,
  1061. "role": user.role,
  1062. },
  1063. "__metadata__": metadata,
  1064. "__request__": request,
  1065. "__model__": model,
  1066. }
  1067. filter_functions = [
  1068. Functions.get_function_by_id(filter_id)
  1069. for filter_id in get_sorted_filter_ids(
  1070. request, model, metadata.get("filter_ids", [])
  1071. )
  1072. ]
  1073. # Streaming response
  1074. if event_emitter and event_caller:
  1075. task_id = str(uuid4()) # Create a unique task ID.
  1076. model_id = form_data.get("model", "")
  1077. Chats.upsert_message_to_chat_by_id_and_message_id(
  1078. metadata["chat_id"],
  1079. metadata["message_id"],
  1080. {
  1081. "model": model_id,
  1082. },
  1083. )
  1084. def split_content_and_whitespace(content):
  1085. content_stripped = content.rstrip()
  1086. original_whitespace = (
  1087. content[len(content_stripped) :]
  1088. if len(content) > len(content_stripped)
  1089. else ""
  1090. )
  1091. return content_stripped, original_whitespace
  1092. def is_opening_code_block(content):
  1093. backtick_segments = content.split("```")
  1094. # Even number of segments means the last backticks are opening a new block
  1095. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  1096. # Handle as a background task
  1097. async def post_response_handler(response, events):
  1098. def serialize_content_blocks(content_blocks, raw=False):
  1099. content = ""
  1100. for block in content_blocks:
  1101. if block["type"] == "text":
  1102. content = f"{content}{block['content'].strip()}\n"
  1103. elif block["type"] == "tool_calls":
  1104. attributes = block.get("attributes", {})
  1105. tool_calls = block.get("content", [])
  1106. results = block.get("results", [])
  1107. if results:
  1108. tool_calls_display_content = ""
  1109. for tool_call in tool_calls:
  1110. tool_call_id = tool_call.get("id", "")
  1111. tool_name = tool_call.get("function", {}).get(
  1112. "name", ""
  1113. )
  1114. tool_arguments = tool_call.get("function", {}).get(
  1115. "arguments", ""
  1116. )
  1117. tool_result = None
  1118. tool_result_files = None
  1119. for result in results:
  1120. if tool_call_id == result.get("tool_call_id", ""):
  1121. tool_result = result.get("content", None)
  1122. tool_result_files = result.get("files", None)
  1123. break
  1124. if tool_result:
  1125. tool_calls_display_content = f'{tool_calls_display_content}\n<details type="tool_calls" done="true" id="{tool_call_id}" name="{tool_name}" arguments="{html.escape(json.dumps(tool_arguments))}" result="{html.escape(json.dumps(tool_result))}" files="{html.escape(json.dumps(tool_result_files)) if tool_result_files else ""}">\n<summary>Tool Executed</summary>\n</details>\n'
  1126. else:
  1127. tool_calls_display_content = f'{tool_calls_display_content}\n<details type="tool_calls" done="false" id="{tool_call_id}" name="{tool_name}" arguments="{html.escape(json.dumps(tool_arguments))}">\n<summary>Executing...</summary>\n</details>'
  1128. if not raw:
  1129. content = f"{content}\n{tool_calls_display_content}\n\n"
  1130. else:
  1131. tool_calls_display_content = ""
  1132. for tool_call in tool_calls:
  1133. tool_call_id = tool_call.get("id", "")
  1134. tool_name = tool_call.get("function", {}).get(
  1135. "name", ""
  1136. )
  1137. tool_arguments = tool_call.get("function", {}).get(
  1138. "arguments", ""
  1139. )
  1140. tool_calls_display_content = f'{tool_calls_display_content}\n<details type="tool_calls" done="false" id="{tool_call_id}" name="{tool_name}" arguments="{html.escape(json.dumps(tool_arguments))}">\n<summary>Executing...</summary>\n</details>'
  1141. if not raw:
  1142. content = f"{content}\n{tool_calls_display_content}\n\n"
  1143. elif block["type"] == "reasoning":
  1144. reasoning_display_content = "\n".join(
  1145. (f"> {line}" if not line.startswith(">") else line)
  1146. for line in block["content"].splitlines()
  1147. )
  1148. reasoning_duration = block.get("duration", None)
  1149. if reasoning_duration is not None:
  1150. if raw:
  1151. content = f'{content}\n<{block["start_tag"]}>{block["content"]}<{block["end_tag"]}>\n'
  1152. else:
  1153. 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'
  1154. else:
  1155. if raw:
  1156. content = f'{content}\n<{block["start_tag"]}>{block["content"]}<{block["end_tag"]}>\n'
  1157. else:
  1158. content = f'{content}\n<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1159. elif block["type"] == "code_interpreter":
  1160. attributes = block.get("attributes", {})
  1161. output = block.get("output", None)
  1162. lang = attributes.get("lang", "")
  1163. content_stripped, original_whitespace = (
  1164. split_content_and_whitespace(content)
  1165. )
  1166. if is_opening_code_block(content_stripped):
  1167. # Remove trailing backticks that would open a new block
  1168. content = (
  1169. content_stripped.rstrip("`").rstrip()
  1170. + original_whitespace
  1171. )
  1172. else:
  1173. # Keep content as is - either closing backticks or no backticks
  1174. content = content_stripped + original_whitespace
  1175. if output:
  1176. output = html.escape(json.dumps(output))
  1177. if raw:
  1178. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1179. else:
  1180. 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'
  1181. else:
  1182. if raw:
  1183. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1184. else:
  1185. content = f'{content}\n<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1186. else:
  1187. block_content = str(block["content"]).strip()
  1188. content = f"{content}{block['type']}: {block_content}\n"
  1189. return content.strip()
  1190. def convert_content_blocks_to_messages(content_blocks):
  1191. messages = []
  1192. temp_blocks = []
  1193. for idx, block in enumerate(content_blocks):
  1194. if block["type"] == "tool_calls":
  1195. messages.append(
  1196. {
  1197. "role": "assistant",
  1198. "content": serialize_content_blocks(temp_blocks),
  1199. "tool_calls": block.get("content"),
  1200. }
  1201. )
  1202. results = block.get("results", [])
  1203. for result in results:
  1204. messages.append(
  1205. {
  1206. "role": "tool",
  1207. "tool_call_id": result["tool_call_id"],
  1208. "content": result["content"],
  1209. }
  1210. )
  1211. temp_blocks = []
  1212. else:
  1213. temp_blocks.append(block)
  1214. if temp_blocks:
  1215. content = serialize_content_blocks(temp_blocks)
  1216. if content:
  1217. messages.append(
  1218. {
  1219. "role": "assistant",
  1220. "content": content,
  1221. }
  1222. )
  1223. return messages
  1224. def tag_content_handler(content_type, tags, content, content_blocks):
  1225. end_flag = False
  1226. def extract_attributes(tag_content):
  1227. """Extract attributes from a tag if they exist."""
  1228. attributes = {}
  1229. if not tag_content: # Ensure tag_content is not None
  1230. return attributes
  1231. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1232. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1233. for key, value in matches:
  1234. attributes[key] = value
  1235. return attributes
  1236. if content_blocks[-1]["type"] == "text":
  1237. for start_tag, end_tag in tags:
  1238. # Match start tag e.g., <tag> or <tag attr="value">
  1239. start_tag_pattern = rf"<{re.escape(start_tag)}(\s.*?)?>"
  1240. match = re.search(start_tag_pattern, content)
  1241. if match:
  1242. attr_content = (
  1243. match.group(1) if match.group(1) else ""
  1244. ) # Ensure it's not None
  1245. attributes = extract_attributes(
  1246. attr_content
  1247. ) # Extract attributes safely
  1248. # Capture everything before and after the matched tag
  1249. before_tag = content[
  1250. : match.start()
  1251. ] # Content before opening tag
  1252. after_tag = content[
  1253. match.end() :
  1254. ] # Content after opening tag
  1255. # Remove the start tag and after from the currently handling text block
  1256. content_blocks[-1]["content"] = content_blocks[-1][
  1257. "content"
  1258. ].replace(match.group(0) + after_tag, "")
  1259. if before_tag:
  1260. content_blocks[-1]["content"] = before_tag
  1261. if not content_blocks[-1]["content"]:
  1262. content_blocks.pop()
  1263. # Append the new block
  1264. content_blocks.append(
  1265. {
  1266. "type": content_type,
  1267. "start_tag": start_tag,
  1268. "end_tag": end_tag,
  1269. "attributes": attributes,
  1270. "content": "",
  1271. "started_at": time.time(),
  1272. }
  1273. )
  1274. if after_tag:
  1275. content_blocks[-1]["content"] = after_tag
  1276. tag_content_handler(
  1277. content_type, tags, after_tag, content_blocks
  1278. )
  1279. break
  1280. elif content_blocks[-1]["type"] == content_type:
  1281. start_tag = content_blocks[-1]["start_tag"]
  1282. end_tag = content_blocks[-1]["end_tag"]
  1283. # Match end tag e.g., </tag>
  1284. end_tag_pattern = rf"<{re.escape(end_tag)}>"
  1285. # Check if the content has the end tag
  1286. if re.search(end_tag_pattern, content):
  1287. end_flag = True
  1288. block_content = content_blocks[-1]["content"]
  1289. # Strip start and end tags from the content
  1290. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1291. block_content = re.sub(
  1292. start_tag_pattern, "", block_content
  1293. ).strip()
  1294. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1295. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1296. # Content inside the tag
  1297. block_content = (
  1298. split_content[0].strip() if split_content else ""
  1299. )
  1300. # Leftover content (everything after `</tag>`)
  1301. leftover_content = (
  1302. split_content[1].strip() if len(split_content) > 1 else ""
  1303. )
  1304. if block_content:
  1305. content_blocks[-1]["content"] = block_content
  1306. content_blocks[-1]["ended_at"] = time.time()
  1307. content_blocks[-1]["duration"] = int(
  1308. content_blocks[-1]["ended_at"]
  1309. - content_blocks[-1]["started_at"]
  1310. )
  1311. # Reset the content_blocks by appending a new text block
  1312. if content_type != "code_interpreter":
  1313. if leftover_content:
  1314. content_blocks.append(
  1315. {
  1316. "type": "text",
  1317. "content": leftover_content,
  1318. }
  1319. )
  1320. else:
  1321. content_blocks.append(
  1322. {
  1323. "type": "text",
  1324. "content": "",
  1325. }
  1326. )
  1327. else:
  1328. # Remove the block if content is empty
  1329. content_blocks.pop()
  1330. if leftover_content:
  1331. content_blocks.append(
  1332. {
  1333. "type": "text",
  1334. "content": leftover_content,
  1335. }
  1336. )
  1337. else:
  1338. content_blocks.append(
  1339. {
  1340. "type": "text",
  1341. "content": "",
  1342. }
  1343. )
  1344. # Clean processed content
  1345. content = re.sub(
  1346. rf"<{re.escape(start_tag)}(.*?)>(.|\n)*?<{re.escape(end_tag)}>",
  1347. "",
  1348. content,
  1349. flags=re.DOTALL,
  1350. )
  1351. return content, content_blocks, end_flag
  1352. message = Chats.get_message_by_id_and_message_id(
  1353. metadata["chat_id"], metadata["message_id"]
  1354. )
  1355. tool_calls = []
  1356. last_assistant_message = None
  1357. try:
  1358. if form_data["messages"][-1]["role"] == "assistant":
  1359. last_assistant_message = get_last_assistant_message(
  1360. form_data["messages"]
  1361. )
  1362. except Exception as e:
  1363. pass
  1364. content = (
  1365. message.get("content", "")
  1366. if message
  1367. else last_assistant_message if last_assistant_message else ""
  1368. )
  1369. content_blocks = [
  1370. {
  1371. "type": "text",
  1372. "content": content,
  1373. }
  1374. ]
  1375. # We might want to disable this by default
  1376. DETECT_REASONING = True
  1377. DETECT_SOLUTION = True
  1378. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1379. "code_interpreter", False
  1380. )
  1381. reasoning_tags = [
  1382. ("think", "/think"),
  1383. ("thinking", "/thinking"),
  1384. ("reason", "/reason"),
  1385. ("reasoning", "/reasoning"),
  1386. ("thought", "/thought"),
  1387. ("Thought", "/Thought"),
  1388. ("|begin_of_thought|", "|end_of_thought|"),
  1389. ]
  1390. code_interpreter_tags = [("code_interpreter", "/code_interpreter")]
  1391. solution_tags = [("|begin_of_solution|", "|end_of_solution|")]
  1392. try:
  1393. for event in events:
  1394. await event_emitter(
  1395. {
  1396. "type": "chat:completion",
  1397. "data": event,
  1398. }
  1399. )
  1400. # Save message in the database
  1401. Chats.upsert_message_to_chat_by_id_and_message_id(
  1402. metadata["chat_id"],
  1403. metadata["message_id"],
  1404. {
  1405. **event,
  1406. },
  1407. )
  1408. async def stream_body_handler(response):
  1409. nonlocal content
  1410. nonlocal content_blocks
  1411. response_tool_calls = []
  1412. async for line in response.body_iterator:
  1413. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1414. data = line
  1415. # Skip empty lines
  1416. if not data.strip():
  1417. continue
  1418. # "data:" is the prefix for each event
  1419. if not data.startswith("data:"):
  1420. continue
  1421. # Remove the prefix
  1422. data = data[len("data:") :].strip()
  1423. try:
  1424. data = json.loads(data)
  1425. data, _ = await process_filter_functions(
  1426. request=request,
  1427. filter_functions=filter_functions,
  1428. filter_type="stream",
  1429. form_data=data,
  1430. extra_params=extra_params,
  1431. )
  1432. if data:
  1433. if "event" in data:
  1434. await event_emitter(data.get("event", {}))
  1435. if "selected_model_id" in data:
  1436. model_id = data["selected_model_id"]
  1437. Chats.upsert_message_to_chat_by_id_and_message_id(
  1438. metadata["chat_id"],
  1439. metadata["message_id"],
  1440. {
  1441. "selectedModelId": model_id,
  1442. },
  1443. )
  1444. else:
  1445. choices = data.get("choices", [])
  1446. if not choices:
  1447. error = data.get("error", {})
  1448. if error:
  1449. await event_emitter(
  1450. {
  1451. "type": "chat:completion",
  1452. "data": {
  1453. "error": error,
  1454. },
  1455. }
  1456. )
  1457. usage = data.get("usage", {})
  1458. if usage:
  1459. await event_emitter(
  1460. {
  1461. "type": "chat:completion",
  1462. "data": {
  1463. "usage": usage,
  1464. },
  1465. }
  1466. )
  1467. continue
  1468. delta = choices[0].get("delta", {})
  1469. delta_tool_calls = delta.get("tool_calls", None)
  1470. if delta_tool_calls:
  1471. for delta_tool_call in delta_tool_calls:
  1472. tool_call_index = delta_tool_call.get(
  1473. "index"
  1474. )
  1475. if tool_call_index is not None:
  1476. # Check if the tool call already exists
  1477. current_response_tool_call = None
  1478. for (
  1479. response_tool_call
  1480. ) in response_tool_calls:
  1481. if (
  1482. response_tool_call.get("index")
  1483. == tool_call_index
  1484. ):
  1485. current_response_tool_call = (
  1486. response_tool_call
  1487. )
  1488. break
  1489. if current_response_tool_call is None:
  1490. # Add the new tool call
  1491. delta_tool_call.setdefault(
  1492. "function", {}
  1493. )
  1494. delta_tool_call[
  1495. "function"
  1496. ].setdefault("name", "")
  1497. delta_tool_call[
  1498. "function"
  1499. ].setdefault("arguments", "")
  1500. response_tool_calls.append(
  1501. delta_tool_call
  1502. )
  1503. else:
  1504. # Update the existing tool call
  1505. delta_name = delta_tool_call.get(
  1506. "function", {}
  1507. ).get("name")
  1508. delta_arguments = (
  1509. delta_tool_call.get(
  1510. "function", {}
  1511. ).get("arguments")
  1512. )
  1513. if delta_name:
  1514. current_response_tool_call[
  1515. "function"
  1516. ]["name"] += delta_name
  1517. if delta_arguments:
  1518. current_response_tool_call[
  1519. "function"
  1520. ][
  1521. "arguments"
  1522. ] += delta_arguments
  1523. value = delta.get("content")
  1524. reasoning_content = delta.get(
  1525. "reasoning_content"
  1526. ) or delta.get("reasoning")
  1527. if reasoning_content:
  1528. if (
  1529. not content_blocks
  1530. or content_blocks[-1]["type"] != "reasoning"
  1531. ):
  1532. reasoning_block = {
  1533. "type": "reasoning",
  1534. "start_tag": "think",
  1535. "end_tag": "/think",
  1536. "attributes": {
  1537. "type": "reasoning_content"
  1538. },
  1539. "content": "",
  1540. "started_at": time.time(),
  1541. }
  1542. content_blocks.append(reasoning_block)
  1543. else:
  1544. reasoning_block = content_blocks[-1]
  1545. reasoning_block["content"] += reasoning_content
  1546. data = {
  1547. "content": serialize_content_blocks(
  1548. content_blocks
  1549. )
  1550. }
  1551. if value:
  1552. if (
  1553. content_blocks
  1554. and content_blocks[-1]["type"]
  1555. == "reasoning"
  1556. and content_blocks[-1]
  1557. .get("attributes", {})
  1558. .get("type")
  1559. == "reasoning_content"
  1560. ):
  1561. reasoning_block = content_blocks[-1]
  1562. reasoning_block["ended_at"] = time.time()
  1563. reasoning_block["duration"] = int(
  1564. reasoning_block["ended_at"]
  1565. - reasoning_block["started_at"]
  1566. )
  1567. content_blocks.append(
  1568. {
  1569. "type": "text",
  1570. "content": "",
  1571. }
  1572. )
  1573. content = f"{content}{value}"
  1574. if not content_blocks:
  1575. content_blocks.append(
  1576. {
  1577. "type": "text",
  1578. "content": "",
  1579. }
  1580. )
  1581. content_blocks[-1]["content"] = (
  1582. content_blocks[-1]["content"] + value
  1583. )
  1584. if DETECT_REASONING:
  1585. content, content_blocks, _ = (
  1586. tag_content_handler(
  1587. "reasoning",
  1588. reasoning_tags,
  1589. content,
  1590. content_blocks,
  1591. )
  1592. )
  1593. if DETECT_CODE_INTERPRETER:
  1594. content, content_blocks, end = (
  1595. tag_content_handler(
  1596. "code_interpreter",
  1597. code_interpreter_tags,
  1598. content,
  1599. content_blocks,
  1600. )
  1601. )
  1602. if end:
  1603. break
  1604. if DETECT_SOLUTION:
  1605. content, content_blocks, _ = (
  1606. tag_content_handler(
  1607. "solution",
  1608. solution_tags,
  1609. content,
  1610. content_blocks,
  1611. )
  1612. )
  1613. if ENABLE_REALTIME_CHAT_SAVE:
  1614. # Save message in the database
  1615. Chats.upsert_message_to_chat_by_id_and_message_id(
  1616. metadata["chat_id"],
  1617. metadata["message_id"],
  1618. {
  1619. "content": serialize_content_blocks(
  1620. content_blocks
  1621. ),
  1622. },
  1623. )
  1624. else:
  1625. data = {
  1626. "content": serialize_content_blocks(
  1627. content_blocks
  1628. ),
  1629. }
  1630. await event_emitter(
  1631. {
  1632. "type": "chat:completion",
  1633. "data": data,
  1634. }
  1635. )
  1636. except Exception as e:
  1637. done = "data: [DONE]" in line
  1638. if done:
  1639. pass
  1640. else:
  1641. log.debug("Error: ", e)
  1642. continue
  1643. if content_blocks:
  1644. # Clean up the last text block
  1645. if content_blocks[-1]["type"] == "text":
  1646. content_blocks[-1]["content"] = content_blocks[-1][
  1647. "content"
  1648. ].strip()
  1649. if not content_blocks[-1]["content"]:
  1650. content_blocks.pop()
  1651. if not content_blocks:
  1652. content_blocks.append(
  1653. {
  1654. "type": "text",
  1655. "content": "",
  1656. }
  1657. )
  1658. if response_tool_calls:
  1659. tool_calls.append(response_tool_calls)
  1660. if response.background:
  1661. await response.background()
  1662. await stream_body_handler(response)
  1663. MAX_TOOL_CALL_RETRIES = 10
  1664. tool_call_retries = 0
  1665. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1666. tool_call_retries += 1
  1667. response_tool_calls = tool_calls.pop(0)
  1668. content_blocks.append(
  1669. {
  1670. "type": "tool_calls",
  1671. "content": response_tool_calls,
  1672. }
  1673. )
  1674. await event_emitter(
  1675. {
  1676. "type": "chat:completion",
  1677. "data": {
  1678. "content": serialize_content_blocks(content_blocks),
  1679. },
  1680. }
  1681. )
  1682. tools = metadata.get("tools", {})
  1683. results = []
  1684. for tool_call in response_tool_calls:
  1685. tool_call_id = tool_call.get("id", "")
  1686. tool_name = tool_call.get("function", {}).get("name", "")
  1687. tool_call_args = tool_call.get("function", {}).get("arguments", "{}")
  1688. tool_function_params = {}
  1689. try:
  1690. # json.loads cannot be used because some models do not produce valid JSON
  1691. tool_function_params = ast.literal_eval(
  1692. tool_call_args
  1693. )
  1694. except Exception as e:
  1695. log.debug(e)
  1696. # Fallback to JSON parsing
  1697. try:
  1698. tool_function_params = json.loads(
  1699. tool_call_args
  1700. )
  1701. except Exception as e:
  1702. log.error(
  1703. f"Error parsing tool call arguments: {tool_call_args}"
  1704. )
  1705. # Mutate the original tool call response params as they are passed back to the passed
  1706. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  1707. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  1708. # params are not valid json.
  1709. # Main case so far is no args = "" = invalid json.
  1710. log.debug(f"Parsed args from {tool_call_args} to {tool_function_params}")
  1711. tool_call.setdefault("function", {})["arguments"] = json.dumps(tool_function_params)
  1712. tool_result = None
  1713. if tool_name in tools:
  1714. tool = tools[tool_name]
  1715. spec = tool.get("spec", {})
  1716. try:
  1717. allowed_params = (
  1718. spec.get("parameters", {})
  1719. .get("properties", {})
  1720. .keys()
  1721. )
  1722. tool_function_params = {
  1723. k: v
  1724. for k, v in tool_function_params.items()
  1725. if k in allowed_params
  1726. }
  1727. if tool.get("direct", False):
  1728. tool_result = await event_caller(
  1729. {
  1730. "type": "execute:tool",
  1731. "data": {
  1732. "id": str(uuid4()),
  1733. "name": tool_name,
  1734. "params": tool_function_params,
  1735. "server": tool.get("server", {}),
  1736. "session_id": metadata.get(
  1737. "session_id", None
  1738. ),
  1739. },
  1740. }
  1741. )
  1742. else:
  1743. tool_function = tool["callable"]
  1744. tool_result = await tool_function(
  1745. **tool_function_params
  1746. )
  1747. except Exception as e:
  1748. tool_result = str(e)
  1749. tool_result_files = []
  1750. if isinstance(tool_result, list):
  1751. for item in tool_result:
  1752. # check if string
  1753. if isinstance(item, str) and item.startswith("data:"):
  1754. tool_result_files.append(item)
  1755. tool_result.remove(item)
  1756. if isinstance(tool_result, dict) or isinstance(
  1757. tool_result, list
  1758. ):
  1759. tool_result = json.dumps(tool_result, indent=2)
  1760. results.append(
  1761. {
  1762. "tool_call_id": tool_call_id,
  1763. "content": tool_result,
  1764. **(
  1765. {"files": tool_result_files}
  1766. if tool_result_files
  1767. else {}
  1768. ),
  1769. }
  1770. )
  1771. content_blocks[-1]["results"] = results
  1772. content_blocks.append(
  1773. {
  1774. "type": "text",
  1775. "content": "",
  1776. }
  1777. )
  1778. await event_emitter(
  1779. {
  1780. "type": "chat:completion",
  1781. "data": {
  1782. "content": serialize_content_blocks(content_blocks),
  1783. },
  1784. }
  1785. )
  1786. try:
  1787. res = await generate_chat_completion(
  1788. request,
  1789. {
  1790. "model": model_id,
  1791. "stream": True,
  1792. "tools": form_data["tools"],
  1793. "messages": [
  1794. *form_data["messages"],
  1795. *convert_content_blocks_to_messages(content_blocks),
  1796. ],
  1797. },
  1798. user,
  1799. )
  1800. if isinstance(res, StreamingResponse):
  1801. await stream_body_handler(res)
  1802. else:
  1803. break
  1804. except Exception as e:
  1805. log.debug(e)
  1806. break
  1807. if DETECT_CODE_INTERPRETER:
  1808. MAX_RETRIES = 5
  1809. retries = 0
  1810. while (
  1811. content_blocks[-1]["type"] == "code_interpreter"
  1812. and retries < MAX_RETRIES
  1813. ):
  1814. await event_emitter(
  1815. {
  1816. "type": "chat:completion",
  1817. "data": {
  1818. "content": serialize_content_blocks(content_blocks),
  1819. },
  1820. }
  1821. )
  1822. retries += 1
  1823. log.debug(f"Attempt count: {retries}")
  1824. output = ""
  1825. try:
  1826. if content_blocks[-1]["attributes"].get("type") == "code":
  1827. code = content_blocks[-1]["content"]
  1828. if (
  1829. request.app.state.config.CODE_INTERPRETER_ENGINE
  1830. == "pyodide"
  1831. ):
  1832. output = await event_caller(
  1833. {
  1834. "type": "execute:python",
  1835. "data": {
  1836. "id": str(uuid4()),
  1837. "code": code,
  1838. "session_id": metadata.get(
  1839. "session_id", None
  1840. ),
  1841. },
  1842. }
  1843. )
  1844. elif (
  1845. request.app.state.config.CODE_INTERPRETER_ENGINE
  1846. == "jupyter"
  1847. ):
  1848. output = await execute_code_jupyter(
  1849. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  1850. code,
  1851. (
  1852. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  1853. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1854. == "token"
  1855. else None
  1856. ),
  1857. (
  1858. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  1859. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1860. == "password"
  1861. else None
  1862. ),
  1863. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  1864. )
  1865. else:
  1866. output = {
  1867. "stdout": "Code interpreter engine not configured."
  1868. }
  1869. log.debug(f"Code interpreter output: {output}")
  1870. if isinstance(output, dict):
  1871. stdout = output.get("stdout", "")
  1872. if isinstance(stdout, str):
  1873. stdoutLines = stdout.split("\n")
  1874. for idx, line in enumerate(stdoutLines):
  1875. if "data:image/png;base64" in line:
  1876. id = str(uuid4())
  1877. # ensure the path exists
  1878. os.makedirs(
  1879. os.path.join(CACHE_DIR, "images"),
  1880. exist_ok=True,
  1881. )
  1882. image_path = os.path.join(
  1883. CACHE_DIR,
  1884. f"images/{id}.png",
  1885. )
  1886. with open(image_path, "wb") as f:
  1887. f.write(
  1888. base64.b64decode(
  1889. line.split(",")[1]
  1890. )
  1891. )
  1892. stdoutLines[idx] = (
  1893. f"![Output Image {idx}](/cache/images/{id}.png)"
  1894. )
  1895. output["stdout"] = "\n".join(stdoutLines)
  1896. result = output.get("result", "")
  1897. if isinstance(result, str):
  1898. resultLines = result.split("\n")
  1899. for idx, line in enumerate(resultLines):
  1900. if "data:image/png;base64" in line:
  1901. id = str(uuid4())
  1902. # ensure the path exists
  1903. os.makedirs(
  1904. os.path.join(CACHE_DIR, "images"),
  1905. exist_ok=True,
  1906. )
  1907. image_path = os.path.join(
  1908. CACHE_DIR,
  1909. f"images/{id}.png",
  1910. )
  1911. with open(image_path, "wb") as f:
  1912. f.write(
  1913. base64.b64decode(
  1914. line.split(",")[1]
  1915. )
  1916. )
  1917. resultLines[idx] = (
  1918. f"![Output Image {idx}](/cache/images/{id}.png)"
  1919. )
  1920. output["result"] = "\n".join(resultLines)
  1921. except Exception as e:
  1922. output = str(e)
  1923. content_blocks[-1]["output"] = output
  1924. content_blocks.append(
  1925. {
  1926. "type": "text",
  1927. "content": "",
  1928. }
  1929. )
  1930. await event_emitter(
  1931. {
  1932. "type": "chat:completion",
  1933. "data": {
  1934. "content": serialize_content_blocks(content_blocks),
  1935. },
  1936. }
  1937. )
  1938. try:
  1939. res = await generate_chat_completion(
  1940. request,
  1941. {
  1942. "model": model_id,
  1943. "stream": True,
  1944. "messages": [
  1945. *form_data["messages"],
  1946. {
  1947. "role": "assistant",
  1948. "content": serialize_content_blocks(
  1949. content_blocks, raw=True
  1950. ),
  1951. },
  1952. ],
  1953. },
  1954. user,
  1955. )
  1956. if isinstance(res, StreamingResponse):
  1957. await stream_body_handler(res)
  1958. else:
  1959. break
  1960. except Exception as e:
  1961. log.debug(e)
  1962. break
  1963. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1964. data = {
  1965. "done": True,
  1966. "content": serialize_content_blocks(content_blocks),
  1967. "title": title,
  1968. }
  1969. if not ENABLE_REALTIME_CHAT_SAVE:
  1970. # Save message in the database
  1971. Chats.upsert_message_to_chat_by_id_and_message_id(
  1972. metadata["chat_id"],
  1973. metadata["message_id"],
  1974. {
  1975. "content": serialize_content_blocks(content_blocks),
  1976. },
  1977. )
  1978. # Send a webhook notification if the user is not active
  1979. if not get_active_status_by_user_id(user.id):
  1980. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1981. if webhook_url:
  1982. post_webhook(
  1983. request.app.state.WEBUI_NAME,
  1984. webhook_url,
  1985. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1986. {
  1987. "action": "chat",
  1988. "message": content,
  1989. "title": title,
  1990. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1991. },
  1992. )
  1993. await event_emitter(
  1994. {
  1995. "type": "chat:completion",
  1996. "data": data,
  1997. }
  1998. )
  1999. await background_tasks_handler()
  2000. except asyncio.CancelledError:
  2001. log.warning("Task was cancelled!")
  2002. await event_emitter({"type": "task-cancelled"})
  2003. if not ENABLE_REALTIME_CHAT_SAVE:
  2004. # Save message in the database
  2005. Chats.upsert_message_to_chat_by_id_and_message_id(
  2006. metadata["chat_id"],
  2007. metadata["message_id"],
  2008. {
  2009. "content": serialize_content_blocks(content_blocks),
  2010. },
  2011. )
  2012. if response.background is not None:
  2013. await response.background()
  2014. # background_tasks.add_task(post_response_handler, response, events)
  2015. task_id, _ = create_task(
  2016. post_response_handler(response, events), id=metadata["chat_id"]
  2017. )
  2018. return {"status": True, "task_id": task_id}
  2019. else:
  2020. # Fallback to the original response
  2021. async def stream_wrapper(original_generator, events):
  2022. def wrap_item(item):
  2023. return f"data: {item}\n\n"
  2024. for event in events:
  2025. event, _ = await process_filter_functions(
  2026. request=request,
  2027. filter_functions=filter_functions,
  2028. filter_type="stream",
  2029. form_data=event,
  2030. extra_params=extra_params,
  2031. )
  2032. if event:
  2033. yield wrap_item(json.dumps(event))
  2034. async for data in original_generator:
  2035. data, _ = await process_filter_functions(
  2036. request=request,
  2037. filter_functions=filter_functions,
  2038. filter_type="stream",
  2039. form_data=data,
  2040. extra_params=extra_params,
  2041. )
  2042. if data:
  2043. yield data
  2044. return StreamingResponse(
  2045. stream_wrapper(response.body_iterator, events),
  2046. headers=dict(response.headers),
  2047. background=response.background,
  2048. )