1
0

middleware.py 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073
  1. import time
  2. import logging
  3. import sys
  4. import os
  5. import base64
  6. import textwrap
  7. import asyncio
  8. from aiocache import cached
  9. from typing import Any, Optional
  10. import random
  11. import json
  12. import html
  13. import inspect
  14. import re
  15. import ast
  16. from uuid import uuid4
  17. from concurrent.futures import ThreadPoolExecutor
  18. from fastapi import Request, HTTPException
  19. from fastapi.responses import HTMLResponse
  20. from starlette.responses import Response, StreamingResponse, JSONResponse
  21. from open_webui.models.oauth_sessions import OAuthSessions
  22. from open_webui.models.chats import Chats
  23. from open_webui.models.folders import Folders
  24. from open_webui.models.users import Users
  25. from open_webui.socket.main import (
  26. get_event_call,
  27. get_event_emitter,
  28. get_active_status_by_user_id,
  29. )
  30. from open_webui.routers.tasks import (
  31. generate_queries,
  32. generate_title,
  33. generate_follow_ups,
  34. generate_image_prompt,
  35. generate_chat_tags,
  36. )
  37. from open_webui.routers.retrieval import process_web_search, SearchForm
  38. from open_webui.routers.images import (
  39. load_b64_image_data,
  40. image_generations,
  41. GenerateImageForm,
  42. upload_image,
  43. )
  44. from open_webui.routers.pipelines import (
  45. process_pipeline_inlet_filter,
  46. process_pipeline_outlet_filter,
  47. )
  48. from open_webui.routers.memories import query_memory, QueryMemoryForm
  49. from open_webui.utils.webhook import post_webhook
  50. from open_webui.utils.files import (
  51. get_audio_url_from_base64,
  52. get_file_url_from_base64,
  53. get_image_url_from_base64,
  54. )
  55. from open_webui.models.users import UserModel
  56. from open_webui.models.functions import Functions
  57. from open_webui.models.models import Models
  58. from open_webui.retrieval.utils import get_sources_from_items
  59. from open_webui.utils.chat import generate_chat_completion
  60. from open_webui.utils.task import (
  61. get_task_model_id,
  62. rag_template,
  63. tools_function_calling_generation_template,
  64. )
  65. from open_webui.utils.misc import (
  66. deep_update,
  67. get_message_list,
  68. add_or_update_system_message,
  69. add_or_update_user_message,
  70. get_last_user_message,
  71. get_last_assistant_message,
  72. get_system_message,
  73. prepend_to_first_user_message_content,
  74. convert_logit_bias_input_to_json,
  75. )
  76. from open_webui.utils.tools import get_tools
  77. from open_webui.utils.plugin import load_function_module_by_id
  78. from open_webui.utils.filter import (
  79. get_sorted_filter_ids,
  80. process_filter_functions,
  81. )
  82. from open_webui.utils.code_interpreter import execute_code_jupyter
  83. from open_webui.utils.payload import apply_system_prompt_to_body
  84. from open_webui.utils.mcp.client import MCPClient
  85. from open_webui.config import (
  86. CACHE_DIR,
  87. DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  88. DEFAULT_CODE_INTERPRETER_PROMPT,
  89. CODE_INTERPRETER_BLOCKED_MODULES,
  90. )
  91. from open_webui.env import (
  92. SRC_LOG_LEVELS,
  93. GLOBAL_LOG_LEVEL,
  94. CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
  95. CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES,
  96. BYPASS_MODEL_ACCESS_CONTROL,
  97. ENABLE_REALTIME_CHAT_SAVE,
  98. ENABLE_QUERIES_CACHE,
  99. )
  100. from open_webui.constants import TASKS
  101. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  102. log = logging.getLogger(__name__)
  103. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  104. DEFAULT_REASONING_TAGS = [
  105. ("<think>", "</think>"),
  106. ("<thinking>", "</thinking>"),
  107. ("<reason>", "</reason>"),
  108. ("<reasoning>", "</reasoning>"),
  109. ("<thought>", "</thought>"),
  110. ("<Thought>", "</Thought>"),
  111. ("<|begin_of_thought|>", "<|end_of_thought|>"),
  112. ("◁think▷", "◁/think▷"),
  113. ]
  114. DEFAULT_SOLUTION_TAGS = [("<|begin_of_solution|>", "<|end_of_solution|>")]
  115. DEFAULT_CODE_INTERPRETER_TAGS = [("<code_interpreter>", "</code_interpreter>")]
  116. async def chat_completion_tools_handler(
  117. request: Request, body: dict, extra_params: dict, user: UserModel, models, tools
  118. ) -> tuple[dict, dict]:
  119. async def get_content_from_response(response) -> Optional[str]:
  120. content = None
  121. if hasattr(response, "body_iterator"):
  122. async for chunk in response.body_iterator:
  123. data = json.loads(chunk.decode("utf-8"))
  124. content = data["choices"][0]["message"]["content"]
  125. # Cleanup any remaining background tasks if necessary
  126. if response.background is not None:
  127. await response.background()
  128. else:
  129. content = response["choices"][0]["message"]["content"]
  130. return content
  131. def get_tools_function_calling_payload(messages, task_model_id, content):
  132. user_message = get_last_user_message(messages)
  133. recent_messages = messages[-4:] if len(messages) > 4 else messages
  134. chat_history = "\n".join(
  135. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  136. for message in recent_messages
  137. )
  138. prompt = f"History:\n{chat_history}\nQuery: {user_message}"
  139. return {
  140. "model": task_model_id,
  141. "messages": [
  142. {"role": "system", "content": content},
  143. {"role": "user", "content": f"Query: {prompt}"},
  144. ],
  145. "stream": False,
  146. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  147. }
  148. event_caller = extra_params["__event_call__"]
  149. metadata = extra_params["__metadata__"]
  150. task_model_id = get_task_model_id(
  151. body["model"],
  152. request.app.state.config.TASK_MODEL,
  153. request.app.state.config.TASK_MODEL_EXTERNAL,
  154. models,
  155. )
  156. skip_files = False
  157. sources = []
  158. specs = [tool["spec"] for tool in tools.values()]
  159. tools_specs = json.dumps(specs)
  160. if request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  161. template = request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  162. else:
  163. template = DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  164. tools_function_calling_prompt = tools_function_calling_generation_template(
  165. template, tools_specs
  166. )
  167. payload = get_tools_function_calling_payload(
  168. body["messages"], task_model_id, tools_function_calling_prompt
  169. )
  170. try:
  171. response = await generate_chat_completion(request, form_data=payload, user=user)
  172. log.debug(f"{response=}")
  173. content = await get_content_from_response(response)
  174. log.debug(f"{content=}")
  175. if not content:
  176. return body, {}
  177. try:
  178. content = content[content.find("{") : content.rfind("}") + 1]
  179. if not content:
  180. raise Exception("No JSON object found in the response")
  181. result = json.loads(content)
  182. async def tool_call_handler(tool_call):
  183. nonlocal skip_files
  184. log.debug(f"{tool_call=}")
  185. tool_function_name = tool_call.get("name", None)
  186. if tool_function_name not in tools:
  187. return body, {}
  188. tool_function_params = tool_call.get("parameters", {})
  189. try:
  190. tool = tools[tool_function_name]
  191. spec = tool.get("spec", {})
  192. allowed_params = (
  193. spec.get("parameters", {}).get("properties", {}).keys()
  194. )
  195. tool_function_params = {
  196. k: v
  197. for k, v in tool_function_params.items()
  198. if k in allowed_params
  199. }
  200. if tool.get("direct", False):
  201. tool_result = await event_caller(
  202. {
  203. "type": "execute:tool",
  204. "data": {
  205. "id": str(uuid4()),
  206. "name": tool_function_name,
  207. "params": tool_function_params,
  208. "server": tool.get("server", {}),
  209. "session_id": metadata.get("session_id", None),
  210. },
  211. }
  212. )
  213. else:
  214. tool_function = tool["callable"]
  215. tool_result = await tool_function(**tool_function_params)
  216. except Exception as e:
  217. tool_result = str(e)
  218. tool_result_embeds = []
  219. if isinstance(tool_result, HTMLResponse):
  220. content_disposition = tool_result.headers.get(
  221. "Content-Disposition", ""
  222. )
  223. if "inline" in content_disposition:
  224. content = tool_result.body.decode("utf-8")
  225. tool_result_embeds.append(content)
  226. if 200 <= tool_result.status_code < 300:
  227. tool_result = {
  228. "status": "success",
  229. "code": "ui_component",
  230. "message": "Embedded UI result is active and visible to the user.",
  231. }
  232. elif 400 <= tool_result.status_code < 500:
  233. tool_result = {
  234. "status": "error",
  235. "code": "ui_component",
  236. "message": f"Client error {tool_result.status_code} from embedded UI result.",
  237. }
  238. elif 500 <= tool_result.status_code < 600:
  239. tool_result = {
  240. "status": "error",
  241. "code": "ui_component",
  242. "message": f"Server error {tool_result.status_code} from embedded UI result.",
  243. }
  244. else:
  245. tool_result = {
  246. "status": "error",
  247. "code": "ui_component",
  248. "message": f"Unexpected status code {tool_result.status_code} from embedded UI result.",
  249. }
  250. else:
  251. tool_result = tool_result.body.decode("utf-8")
  252. elif (
  253. tool.get("type") == "external" and isinstance(tool_result, tuple)
  254. ) or (
  255. tool.get("direct", True)
  256. and isinstance(tool_result, list)
  257. and len(tool_result) == 2
  258. ):
  259. tool_result, tool_response_headers = tool_result
  260. if tool_response_headers and isinstance(
  261. tool_response_headers, dict
  262. ):
  263. content_disposition = tool_response_headers.get(
  264. "Content-Disposition",
  265. tool_response_headers.get("content-disposition", ""),
  266. )
  267. if "inline" in content_disposition:
  268. content_type = tool_response_headers.get(
  269. "Content-Type",
  270. tool_response_headers.get("content-type", ""),
  271. )
  272. location = tool_response_headers.get(
  273. "Location",
  274. tool_response_headers.get("location", ""),
  275. )
  276. if "text/html" in content_type:
  277. # Display as iframe embed
  278. tool_result_embeds.append(tool_result)
  279. tool_result = {
  280. "status": "success",
  281. "code": "ui_component",
  282. "message": "Embedded UI result is active and visible to the user.",
  283. }
  284. elif location:
  285. tool_result_embeds.append(location)
  286. tool_result = {
  287. "status": "success",
  288. "code": "ui_component",
  289. "message": "Embedded UI result is active and visible to the user.",
  290. }
  291. tool_result_files = []
  292. if isinstance(tool_result, list):
  293. for item in tool_result:
  294. # check if string
  295. if isinstance(item, str) and item.startswith("data:"):
  296. tool_result_files.append(item)
  297. tool_result.remove(item)
  298. if isinstance(tool_result, dict) or isinstance(tool_result, list):
  299. tool_result = json.dumps(tool_result, indent=2)
  300. if isinstance(tool_result, str):
  301. tool = tools[tool_function_name]
  302. tool_id = tool.get("tool_id", "")
  303. tool_name = (
  304. f"{tool_id}/{tool_function_name}"
  305. if tool_id
  306. else f"{tool_function_name}"
  307. )
  308. # Citation is enabled for this tool
  309. sources.append(
  310. {
  311. "source": {
  312. "name": (f"TOOL:{tool_name}"),
  313. },
  314. "document": [tool_result],
  315. "metadata": [
  316. {
  317. "source": (f"TOOL:{tool_name}"),
  318. "parameters": tool_function_params,
  319. }
  320. ],
  321. "tool_result": True,
  322. }
  323. )
  324. # Citation is not enabled for this tool
  325. body["messages"] = add_or_update_user_message(
  326. f"\nTool `{tool_name}` Output: {tool_result}",
  327. body["messages"],
  328. )
  329. if (
  330. tools[tool_function_name]
  331. .get("metadata", {})
  332. .get("file_handler", False)
  333. ):
  334. skip_files = True
  335. # check if "tool_calls" in result
  336. if result.get("tool_calls"):
  337. for tool_call in result.get("tool_calls"):
  338. await tool_call_handler(tool_call)
  339. else:
  340. await tool_call_handler(result)
  341. except Exception as e:
  342. log.debug(f"Error: {e}")
  343. content = None
  344. except Exception as e:
  345. log.debug(f"Error: {e}")
  346. content = None
  347. log.debug(f"tool_contexts: {sources}")
  348. if skip_files and "files" in body.get("metadata", {}):
  349. del body["metadata"]["files"]
  350. return body, {"sources": sources}
  351. async def chat_memory_handler(
  352. request: Request, form_data: dict, extra_params: dict, user
  353. ):
  354. try:
  355. results = await query_memory(
  356. request,
  357. QueryMemoryForm(
  358. **{
  359. "content": get_last_user_message(form_data["messages"]) or "",
  360. "k": 3,
  361. }
  362. ),
  363. user,
  364. )
  365. except Exception as e:
  366. log.debug(e)
  367. results = None
  368. user_context = ""
  369. if results and hasattr(results, "documents"):
  370. if results.documents and len(results.documents) > 0:
  371. for doc_idx, doc in enumerate(results.documents[0]):
  372. created_at_date = "Unknown Date"
  373. if results.metadatas[0][doc_idx].get("created_at"):
  374. created_at_timestamp = results.metadatas[0][doc_idx]["created_at"]
  375. created_at_date = time.strftime(
  376. "%Y-%m-%d", time.localtime(created_at_timestamp)
  377. )
  378. user_context += f"{doc_idx + 1}. [{created_at_date}] {doc}\n"
  379. form_data["messages"] = add_or_update_system_message(
  380. f"User Context:\n{user_context}\n", form_data["messages"], append=True
  381. )
  382. return form_data
  383. async def chat_web_search_handler(
  384. request: Request, form_data: dict, extra_params: dict, user
  385. ):
  386. event_emitter = extra_params["__event_emitter__"]
  387. await event_emitter(
  388. {
  389. "type": "status",
  390. "data": {
  391. "action": "web_search",
  392. "description": "Searching the web",
  393. "done": False,
  394. },
  395. }
  396. )
  397. messages = form_data["messages"]
  398. user_message = get_last_user_message(messages)
  399. queries = []
  400. try:
  401. res = await generate_queries(
  402. request,
  403. {
  404. "model": form_data["model"],
  405. "messages": messages,
  406. "prompt": user_message,
  407. "type": "web_search",
  408. },
  409. user,
  410. )
  411. response = res["choices"][0]["message"]["content"]
  412. try:
  413. bracket_start = response.find("{")
  414. bracket_end = response.rfind("}") + 1
  415. if bracket_start == -1 or bracket_end == -1:
  416. raise Exception("No JSON object found in the response")
  417. response = response[bracket_start:bracket_end]
  418. queries = json.loads(response)
  419. queries = queries.get("queries", [])
  420. except Exception as e:
  421. queries = [response]
  422. if ENABLE_QUERIES_CACHE:
  423. request.state.cached_queries = queries
  424. except Exception as e:
  425. log.exception(e)
  426. queries = [user_message]
  427. # Check if generated queries are empty
  428. if len(queries) == 1 and queries[0].strip() == "":
  429. queries = [user_message]
  430. # Check if queries are not found
  431. if len(queries) == 0:
  432. await event_emitter(
  433. {
  434. "type": "status",
  435. "data": {
  436. "action": "web_search",
  437. "description": "No search query generated",
  438. "done": True,
  439. },
  440. }
  441. )
  442. return form_data
  443. await event_emitter(
  444. {
  445. "type": "status",
  446. "data": {
  447. "action": "web_search_queries_generated",
  448. "queries": queries,
  449. "done": False,
  450. },
  451. }
  452. )
  453. try:
  454. results = await process_web_search(
  455. request,
  456. SearchForm(queries=queries),
  457. user=user,
  458. )
  459. if results:
  460. files = form_data.get("files", [])
  461. if results.get("collection_names"):
  462. for col_idx, collection_name in enumerate(
  463. results.get("collection_names")
  464. ):
  465. files.append(
  466. {
  467. "collection_name": collection_name,
  468. "name": ", ".join(queries),
  469. "type": "web_search",
  470. "urls": results["filenames"],
  471. "queries": queries,
  472. }
  473. )
  474. elif results.get("docs"):
  475. # Invoked when bypass embedding and retrieval is set to True
  476. docs = results["docs"]
  477. files.append(
  478. {
  479. "docs": docs,
  480. "name": ", ".join(queries),
  481. "type": "web_search",
  482. "urls": results["filenames"],
  483. "queries": queries,
  484. }
  485. )
  486. form_data["files"] = files
  487. await event_emitter(
  488. {
  489. "type": "status",
  490. "data": {
  491. "action": "web_search",
  492. "description": "Searched {{count}} sites",
  493. "urls": results["filenames"],
  494. "items": results.get("items", []),
  495. "done": True,
  496. },
  497. }
  498. )
  499. else:
  500. await event_emitter(
  501. {
  502. "type": "status",
  503. "data": {
  504. "action": "web_search",
  505. "description": "No search results found",
  506. "done": True,
  507. "error": True,
  508. },
  509. }
  510. )
  511. except Exception as e:
  512. log.exception(e)
  513. await event_emitter(
  514. {
  515. "type": "status",
  516. "data": {
  517. "action": "web_search",
  518. "description": "An error occurred while searching the web",
  519. "queries": queries,
  520. "done": True,
  521. "error": True,
  522. },
  523. }
  524. )
  525. return form_data
  526. async def chat_image_generation_handler(
  527. request: Request, form_data: dict, extra_params: dict, user
  528. ):
  529. __event_emitter__ = extra_params["__event_emitter__"]
  530. await __event_emitter__(
  531. {
  532. "type": "status",
  533. "data": {"description": "Creating image", "done": False},
  534. }
  535. )
  536. messages = form_data["messages"]
  537. user_message = get_last_user_message(messages)
  538. prompt = user_message
  539. negative_prompt = ""
  540. if request.app.state.config.ENABLE_IMAGE_PROMPT_GENERATION:
  541. try:
  542. res = await generate_image_prompt(
  543. request,
  544. {
  545. "model": form_data["model"],
  546. "messages": messages,
  547. },
  548. user,
  549. )
  550. response = res["choices"][0]["message"]["content"]
  551. try:
  552. bracket_start = response.find("{")
  553. bracket_end = response.rfind("}") + 1
  554. if bracket_start == -1 or bracket_end == -1:
  555. raise Exception("No JSON object found in the response")
  556. response = response[bracket_start:bracket_end]
  557. response = json.loads(response)
  558. prompt = response.get("prompt", [])
  559. except Exception as e:
  560. prompt = user_message
  561. except Exception as e:
  562. log.exception(e)
  563. prompt = user_message
  564. system_message_content = ""
  565. try:
  566. images = await image_generations(
  567. request=request,
  568. form_data=GenerateImageForm(**{"prompt": prompt}),
  569. user=user,
  570. )
  571. await __event_emitter__(
  572. {
  573. "type": "status",
  574. "data": {"description": "Image created", "done": True},
  575. }
  576. )
  577. await __event_emitter__(
  578. {
  579. "type": "files",
  580. "data": {
  581. "files": [
  582. {
  583. "type": "image",
  584. "url": image["url"],
  585. }
  586. for image in images
  587. ]
  588. },
  589. }
  590. )
  591. system_message_content = "<context>User is shown the generated image, tell the user that the image has been generated</context>"
  592. except Exception as e:
  593. log.exception(e)
  594. await __event_emitter__(
  595. {
  596. "type": "status",
  597. "data": {
  598. "description": f"An error occurred while generating an image",
  599. "done": True,
  600. },
  601. }
  602. )
  603. system_message_content = "<context>Unable to generate an image, tell the user that an error occurred</context>"
  604. if system_message_content:
  605. form_data["messages"] = add_or_update_system_message(
  606. system_message_content, form_data["messages"]
  607. )
  608. return form_data
  609. async def chat_completion_files_handler(
  610. request: Request, body: dict, extra_params: dict, user: UserModel
  611. ) -> tuple[dict, dict[str, list]]:
  612. __event_emitter__ = extra_params["__event_emitter__"]
  613. sources = []
  614. if files := body.get("metadata", {}).get("files", None):
  615. # Check if all files are in full context mode
  616. all_full_context = all(item.get("context") == "full" for item in files)
  617. queries = []
  618. if not all_full_context:
  619. try:
  620. queries_response = await generate_queries(
  621. request,
  622. {
  623. "model": body["model"],
  624. "messages": body["messages"],
  625. "type": "retrieval",
  626. },
  627. user,
  628. )
  629. queries_response = queries_response["choices"][0]["message"]["content"]
  630. try:
  631. bracket_start = queries_response.find("{")
  632. bracket_end = queries_response.rfind("}") + 1
  633. if bracket_start == -1 or bracket_end == -1:
  634. raise Exception("No JSON object found in the response")
  635. queries_response = queries_response[bracket_start:bracket_end]
  636. queries_response = json.loads(queries_response)
  637. except Exception as e:
  638. queries_response = {"queries": [queries_response]}
  639. queries = queries_response.get("queries", [])
  640. except:
  641. pass
  642. if len(queries) == 0:
  643. queries = [get_last_user_message(body["messages"])]
  644. if not all_full_context:
  645. await __event_emitter__(
  646. {
  647. "type": "status",
  648. "data": {
  649. "action": "queries_generated",
  650. "queries": queries,
  651. "done": False,
  652. },
  653. }
  654. )
  655. try:
  656. # Offload get_sources_from_items to a separate thread
  657. loop = asyncio.get_running_loop()
  658. with ThreadPoolExecutor() as executor:
  659. sources = await loop.run_in_executor(
  660. executor,
  661. lambda: get_sources_from_items(
  662. request=request,
  663. items=files,
  664. queries=queries,
  665. embedding_function=lambda query, prefix: request.app.state.EMBEDDING_FUNCTION(
  666. query, prefix=prefix, user=user
  667. ),
  668. k=request.app.state.config.TOP_K,
  669. reranking_function=(
  670. (
  671. lambda sentences: request.app.state.RERANKING_FUNCTION(
  672. sentences, user=user
  673. )
  674. )
  675. if request.app.state.RERANKING_FUNCTION
  676. else None
  677. ),
  678. k_reranker=request.app.state.config.TOP_K_RERANKER,
  679. r=request.app.state.config.RELEVANCE_THRESHOLD,
  680. hybrid_bm25_weight=request.app.state.config.HYBRID_BM25_WEIGHT,
  681. hybrid_search=request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  682. full_context=all_full_context
  683. or request.app.state.config.RAG_FULL_CONTEXT,
  684. user=user,
  685. ),
  686. )
  687. except Exception as e:
  688. log.exception(e)
  689. log.debug(f"rag_contexts:sources: {sources}")
  690. unique_ids = set()
  691. for source in sources or []:
  692. if not source or len(source.keys()) == 0:
  693. continue
  694. documents = source.get("document") or []
  695. metadatas = source.get("metadata") or []
  696. src_info = source.get("source") or {}
  697. for index, _ in enumerate(documents):
  698. metadata = metadatas[index] if index < len(metadatas) else None
  699. _id = (
  700. (metadata or {}).get("source")
  701. or (src_info or {}).get("id")
  702. or "N/A"
  703. )
  704. unique_ids.add(_id)
  705. sources_count = len(unique_ids)
  706. await __event_emitter__(
  707. {
  708. "type": "status",
  709. "data": {
  710. "action": "sources_retrieved",
  711. "count": sources_count,
  712. "done": True,
  713. },
  714. }
  715. )
  716. return body, {"sources": sources}
  717. def apply_params_to_form_data(form_data, model):
  718. params = form_data.pop("params", {})
  719. custom_params = params.pop("custom_params", {})
  720. open_webui_params = {
  721. "stream_response": bool,
  722. "stream_delta_chunk_size": int,
  723. "function_calling": str,
  724. "reasoning_tags": list,
  725. "system": str,
  726. }
  727. for key in list(params.keys()):
  728. if key in open_webui_params:
  729. del params[key]
  730. if custom_params:
  731. # Attempt to parse custom_params if they are strings
  732. for key, value in custom_params.items():
  733. if isinstance(value, str):
  734. try:
  735. # Attempt to parse the string as JSON
  736. custom_params[key] = json.loads(value)
  737. except json.JSONDecodeError:
  738. # If it fails, keep the original string
  739. pass
  740. # If custom_params are provided, merge them into params
  741. params = deep_update(params, custom_params)
  742. if model.get("owned_by") == "ollama":
  743. # Ollama specific parameters
  744. form_data["options"] = params
  745. else:
  746. if isinstance(params, dict):
  747. for key, value in params.items():
  748. if value is not None:
  749. form_data[key] = value
  750. if "logit_bias" in params and params["logit_bias"] is not None:
  751. try:
  752. form_data["logit_bias"] = json.loads(
  753. convert_logit_bias_input_to_json(params["logit_bias"])
  754. )
  755. except Exception as e:
  756. log.exception(f"Error parsing logit_bias: {e}")
  757. return form_data
  758. async def process_chat_payload(request, form_data, user, metadata, model):
  759. # Pipeline Inlet -> Filter Inlet -> Chat Memory -> Chat Web Search -> Chat Image Generation
  760. # -> Chat Code Interpreter (Form Data Update) -> (Default) Chat Tools Function Calling
  761. # -> Chat Files
  762. form_data = apply_params_to_form_data(form_data, model)
  763. log.debug(f"form_data: {form_data}")
  764. system_message = get_system_message(form_data.get("messages", []))
  765. if system_message:
  766. try:
  767. form_data = apply_system_prompt_to_body(
  768. system_message.get("content"), form_data, metadata, user
  769. )
  770. except:
  771. pass
  772. event_emitter = get_event_emitter(metadata)
  773. event_call = get_event_call(metadata)
  774. oauth_token = None
  775. try:
  776. if request.cookies.get("oauth_session_id", None):
  777. oauth_token = await request.app.state.oauth_manager.get_oauth_token(
  778. user.id,
  779. request.cookies.get("oauth_session_id", None),
  780. )
  781. except Exception as e:
  782. log.error(f"Error getting OAuth token: {e}")
  783. extra_params = {
  784. "__event_emitter__": event_emitter,
  785. "__event_call__": event_call,
  786. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  787. "__metadata__": metadata,
  788. "__request__": request,
  789. "__model__": model,
  790. "__oauth_token__": oauth_token,
  791. }
  792. # Initialize events to store additional event to be sent to the client
  793. # Initialize contexts and citation
  794. if getattr(request.state, "direct", False) and hasattr(request.state, "model"):
  795. models = {
  796. request.state.model["id"]: request.state.model,
  797. }
  798. else:
  799. models = request.app.state.MODELS
  800. task_model_id = get_task_model_id(
  801. form_data["model"],
  802. request.app.state.config.TASK_MODEL,
  803. request.app.state.config.TASK_MODEL_EXTERNAL,
  804. models,
  805. )
  806. events = []
  807. sources = []
  808. # Folder "Project" handling
  809. # Check if the request has chat_id and is inside of a folder
  810. chat_id = metadata.get("chat_id", None)
  811. if chat_id and user:
  812. chat = Chats.get_chat_by_id_and_user_id(chat_id, user.id)
  813. if chat and chat.folder_id:
  814. folder = Folders.get_folder_by_id_and_user_id(chat.folder_id, user.id)
  815. if folder and folder.data:
  816. if "system_prompt" in folder.data:
  817. form_data = apply_system_prompt_to_body(
  818. folder.data["system_prompt"], form_data, metadata, user
  819. )
  820. if "files" in folder.data:
  821. form_data["files"] = [
  822. *folder.data["files"],
  823. *form_data.get("files", []),
  824. ]
  825. # Model "Knowledge" handling
  826. user_message = get_last_user_message(form_data["messages"])
  827. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  828. if model_knowledge:
  829. await event_emitter(
  830. {
  831. "type": "status",
  832. "data": {
  833. "action": "knowledge_search",
  834. "query": user_message,
  835. "done": False,
  836. },
  837. }
  838. )
  839. knowledge_files = []
  840. for item in model_knowledge:
  841. if item.get("collection_name"):
  842. knowledge_files.append(
  843. {
  844. "id": item.get("collection_name"),
  845. "name": item.get("name"),
  846. "legacy": True,
  847. }
  848. )
  849. elif item.get("collection_names"):
  850. knowledge_files.append(
  851. {
  852. "name": item.get("name"),
  853. "type": "collection",
  854. "collection_names": item.get("collection_names"),
  855. "legacy": True,
  856. }
  857. )
  858. else:
  859. knowledge_files.append(item)
  860. files = form_data.get("files", [])
  861. files.extend(knowledge_files)
  862. form_data["files"] = files
  863. variables = form_data.pop("variables", None)
  864. # Process the form_data through the pipeline
  865. try:
  866. form_data = await process_pipeline_inlet_filter(
  867. request, form_data, user, models
  868. )
  869. except Exception as e:
  870. raise e
  871. try:
  872. filter_functions = [
  873. Functions.get_function_by_id(filter_id)
  874. for filter_id in get_sorted_filter_ids(
  875. request, model, metadata.get("filter_ids", [])
  876. )
  877. ]
  878. form_data, flags = await process_filter_functions(
  879. request=request,
  880. filter_functions=filter_functions,
  881. filter_type="inlet",
  882. form_data=form_data,
  883. extra_params=extra_params,
  884. )
  885. except Exception as e:
  886. raise Exception(f"{e}")
  887. features = form_data.pop("features", None)
  888. if features:
  889. if "memory" in features and features["memory"]:
  890. form_data = await chat_memory_handler(
  891. request, form_data, extra_params, user
  892. )
  893. if "web_search" in features and features["web_search"]:
  894. form_data = await chat_web_search_handler(
  895. request, form_data, extra_params, user
  896. )
  897. if "image_generation" in features and features["image_generation"]:
  898. form_data = await chat_image_generation_handler(
  899. request, form_data, extra_params, user
  900. )
  901. if "code_interpreter" in features and features["code_interpreter"]:
  902. form_data["messages"] = add_or_update_user_message(
  903. (
  904. request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE
  905. if request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE != ""
  906. else DEFAULT_CODE_INTERPRETER_PROMPT
  907. ),
  908. form_data["messages"],
  909. )
  910. tool_ids = form_data.pop("tool_ids", None)
  911. files = form_data.pop("files", None)
  912. # Remove files duplicates
  913. if files:
  914. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  915. metadata = {
  916. **metadata,
  917. "tool_ids": tool_ids,
  918. "files": files,
  919. }
  920. form_data["metadata"] = metadata
  921. # Server side tools
  922. tool_ids = metadata.get("tool_ids", None)
  923. # Client side tools
  924. direct_tool_servers = metadata.get("tool_servers", None)
  925. log.debug(f"{tool_ids=}")
  926. log.debug(f"{direct_tool_servers=}")
  927. tools_dict = {}
  928. mcp_clients = []
  929. mcp_tools_dict = {}
  930. if tool_ids:
  931. for tool_id in tool_ids:
  932. if tool_id.startswith("server:mcp:"):
  933. try:
  934. server_id = tool_id[len("server:mcp:") :]
  935. mcp_server_connection = None
  936. for (
  937. server_connection
  938. ) in request.app.state.config.TOOL_SERVER_CONNECTIONS:
  939. if (
  940. server_connection.get("type", "") == "mcp"
  941. and server_connection.get("info", {}).get("id") == server_id
  942. ):
  943. mcp_server_connection = server_connection
  944. break
  945. if not mcp_server_connection:
  946. log.error(f"MCP server with id {server_id} not found")
  947. continue
  948. auth_type = mcp_server_connection.get("auth_type", "")
  949. headers = {}
  950. if auth_type == "bearer":
  951. headers["Authorization"] = (
  952. f"Bearer {mcp_server_connection.get('key', '')}"
  953. )
  954. elif auth_type == "none":
  955. # No authentication
  956. pass
  957. elif auth_type == "session":
  958. headers["Authorization"] = (
  959. f"Bearer {request.state.token.credentials}"
  960. )
  961. elif auth_type == "system_oauth":
  962. oauth_token = extra_params.get("__oauth_token__", None)
  963. if oauth_token:
  964. headers["Authorization"] = (
  965. f"Bearer {oauth_token.get('access_token', '')}"
  966. )
  967. elif auth_type == "oauth_2.1":
  968. try:
  969. splits = server_id.split(":")
  970. server_id = splits[-1] if len(splits) > 1 else server_id
  971. oauth_token = await request.app.state.oauth_client_manager.get_oauth_token(
  972. user.id, f"mcp:{server_id}"
  973. )
  974. if oauth_token:
  975. headers["Authorization"] = (
  976. f"Bearer {oauth_token.get('access_token', '')}"
  977. )
  978. except Exception as e:
  979. log.error(f"Error getting OAuth token: {e}")
  980. oauth_token = None
  981. mcp_client = MCPClient()
  982. await mcp_client.connect(
  983. url=mcp_server_connection.get("url", ""),
  984. headers=headers if headers else None,
  985. )
  986. tool_specs = await mcp_client.list_tool_specs()
  987. for tool_spec in tool_specs:
  988. def make_tool_function(function_name):
  989. async def tool_function(**kwargs):
  990. return await mcp_client.call_tool(
  991. function_name,
  992. function_args=kwargs,
  993. )
  994. return tool_function
  995. tool_function = make_tool_function(tool_spec["name"])
  996. mcp_tools_dict[tool_spec["name"]] = {
  997. "spec": tool_spec,
  998. "callable": tool_function,
  999. "type": "mcp",
  1000. "client": mcp_client,
  1001. "direct": False,
  1002. }
  1003. mcp_clients.append(mcp_client)
  1004. except Exception as e:
  1005. log.debug(e)
  1006. continue
  1007. tools_dict = await get_tools(
  1008. request,
  1009. tool_ids,
  1010. user,
  1011. {
  1012. **extra_params,
  1013. "__model__": models[task_model_id],
  1014. "__messages__": form_data["messages"],
  1015. "__files__": metadata.get("files", []),
  1016. },
  1017. )
  1018. if mcp_tools_dict:
  1019. tools_dict = {**tools_dict, **mcp_tools_dict}
  1020. if direct_tool_servers:
  1021. for tool_server in direct_tool_servers:
  1022. tool_specs = tool_server.pop("specs", [])
  1023. for tool in tool_specs:
  1024. tools_dict[tool["name"]] = {
  1025. "spec": tool,
  1026. "direct": True,
  1027. "server": tool_server,
  1028. }
  1029. if mcp_clients:
  1030. metadata["mcp_clients"] = mcp_clients
  1031. if tools_dict:
  1032. if metadata.get("params", {}).get("function_calling") == "native":
  1033. # If the function calling is native, then call the tools function calling handler
  1034. metadata["tools"] = tools_dict
  1035. form_data["tools"] = [
  1036. {"type": "function", "function": tool.get("spec", {})}
  1037. for tool in tools_dict.values()
  1038. ]
  1039. else:
  1040. # If the function calling is not native, then call the tools function calling handler
  1041. try:
  1042. form_data, flags = await chat_completion_tools_handler(
  1043. request, form_data, extra_params, user, models, tools_dict
  1044. )
  1045. sources.extend(flags.get("sources", []))
  1046. except Exception as e:
  1047. log.exception(e)
  1048. try:
  1049. form_data, flags = await chat_completion_files_handler(
  1050. request, form_data, extra_params, user
  1051. )
  1052. sources.extend(flags.get("sources", []))
  1053. except Exception as e:
  1054. log.exception(e)
  1055. # If context is not empty, insert it into the messages
  1056. if len(sources) > 0:
  1057. context_string = ""
  1058. citation_idx_map = {}
  1059. for source in sources:
  1060. is_tool_result = source.get("tool_result", False)
  1061. if "document" in source and not is_tool_result:
  1062. for document_text, document_metadata in zip(
  1063. source["document"], source["metadata"]
  1064. ):
  1065. source_name = source.get("source", {}).get("name", None)
  1066. source_id = (
  1067. document_metadata.get("source", None)
  1068. or source.get("source", {}).get("id", None)
  1069. or "N/A"
  1070. )
  1071. if source_id not in citation_idx_map:
  1072. citation_idx_map[source_id] = len(citation_idx_map) + 1
  1073. context_string += (
  1074. f'<source id="{citation_idx_map[source_id]}"'
  1075. + (f' name="{source_name}"' if source_name else "")
  1076. + f">{document_text}</source>\n"
  1077. )
  1078. context_string = context_string.strip()
  1079. prompt = get_last_user_message(form_data["messages"])
  1080. if prompt is None:
  1081. raise Exception("No user message found")
  1082. if context_string != "":
  1083. form_data["messages"] = add_or_update_user_message(
  1084. rag_template(
  1085. request.app.state.config.RAG_TEMPLATE,
  1086. context_string,
  1087. prompt,
  1088. ),
  1089. form_data["messages"],
  1090. append=False,
  1091. )
  1092. # If there are citations, add them to the data_items
  1093. sources = [
  1094. source
  1095. for source in sources
  1096. if source.get("source", {}).get("name", "")
  1097. or source.get("source", {}).get("id", "")
  1098. ]
  1099. if len(sources) > 0:
  1100. events.append({"sources": sources})
  1101. if model_knowledge:
  1102. await event_emitter(
  1103. {
  1104. "type": "status",
  1105. "data": {
  1106. "action": "knowledge_search",
  1107. "query": user_message,
  1108. "done": True,
  1109. "hidden": True,
  1110. },
  1111. }
  1112. )
  1113. return form_data, metadata, events
  1114. async def process_chat_response(
  1115. request, response, form_data, user, metadata, model, events, tasks
  1116. ):
  1117. async def background_tasks_handler():
  1118. messages_map = Chats.get_messages_map_by_chat_id(metadata["chat_id"])
  1119. message = messages_map.get(metadata["message_id"]) if messages_map else None
  1120. if message:
  1121. message_list = get_message_list(messages_map, metadata["message_id"])
  1122. # Remove details tags and files from the messages.
  1123. # as get_message_list creates a new list, it does not affect
  1124. # the original messages outside of this handler
  1125. messages = []
  1126. for message in message_list:
  1127. content = message.get("content", "")
  1128. if isinstance(content, list):
  1129. for item in content:
  1130. if item.get("type") == "text":
  1131. content = item["text"]
  1132. break
  1133. if isinstance(content, str):
  1134. content = re.sub(
  1135. r"<details\b[^>]*>.*?<\/details>|!\[.*?\]\(.*?\)",
  1136. "",
  1137. content,
  1138. flags=re.S | re.I,
  1139. ).strip()
  1140. messages.append(
  1141. {
  1142. **message,
  1143. "role": message.get(
  1144. "role", "assistant"
  1145. ), # Safe fallback for missing role
  1146. "content": content,
  1147. }
  1148. )
  1149. if tasks and messages:
  1150. if (
  1151. TASKS.FOLLOW_UP_GENERATION in tasks
  1152. and tasks[TASKS.FOLLOW_UP_GENERATION]
  1153. ):
  1154. res = await generate_follow_ups(
  1155. request,
  1156. {
  1157. "model": message["model"],
  1158. "messages": messages,
  1159. "message_id": metadata["message_id"],
  1160. "chat_id": metadata["chat_id"],
  1161. },
  1162. user,
  1163. )
  1164. if res and isinstance(res, dict):
  1165. if len(res.get("choices", [])) == 1:
  1166. follow_ups_string = (
  1167. res.get("choices", [])[0]
  1168. .get("message", {})
  1169. .get("content", "")
  1170. )
  1171. else:
  1172. follow_ups_string = ""
  1173. follow_ups_string = follow_ups_string[
  1174. follow_ups_string.find("{") : follow_ups_string.rfind("}")
  1175. + 1
  1176. ]
  1177. try:
  1178. follow_ups = json.loads(follow_ups_string).get(
  1179. "follow_ups", []
  1180. )
  1181. Chats.upsert_message_to_chat_by_id_and_message_id(
  1182. metadata["chat_id"],
  1183. metadata["message_id"],
  1184. {
  1185. "followUps": follow_ups,
  1186. },
  1187. )
  1188. await event_emitter(
  1189. {
  1190. "type": "chat:message:follow_ups",
  1191. "data": {
  1192. "follow_ups": follow_ups,
  1193. },
  1194. }
  1195. )
  1196. except Exception as e:
  1197. pass
  1198. if TASKS.TITLE_GENERATION in tasks:
  1199. user_message = get_last_user_message(messages)
  1200. if user_message and len(user_message) > 100:
  1201. user_message = user_message[:100] + "..."
  1202. if tasks[TASKS.TITLE_GENERATION]:
  1203. res = await generate_title(
  1204. request,
  1205. {
  1206. "model": message["model"],
  1207. "messages": messages,
  1208. "chat_id": metadata["chat_id"],
  1209. },
  1210. user,
  1211. )
  1212. if res and isinstance(res, dict):
  1213. if len(res.get("choices", [])) == 1:
  1214. title_string = (
  1215. res.get("choices", [])[0]
  1216. .get("message", {})
  1217. .get(
  1218. "content", message.get("content", user_message)
  1219. )
  1220. )
  1221. else:
  1222. title_string = ""
  1223. title_string = title_string[
  1224. title_string.find("{") : title_string.rfind("}") + 1
  1225. ]
  1226. try:
  1227. title = json.loads(title_string).get(
  1228. "title", user_message
  1229. )
  1230. except Exception as e:
  1231. title = ""
  1232. if not title:
  1233. title = messages[0].get("content", user_message)
  1234. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1235. await event_emitter(
  1236. {
  1237. "type": "chat:title",
  1238. "data": title,
  1239. }
  1240. )
  1241. elif len(messages) == 2:
  1242. title = messages[0].get("content", user_message)
  1243. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1244. await event_emitter(
  1245. {
  1246. "type": "chat:title",
  1247. "data": message.get("content", user_message),
  1248. }
  1249. )
  1250. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  1251. res = await generate_chat_tags(
  1252. request,
  1253. {
  1254. "model": message["model"],
  1255. "messages": messages,
  1256. "chat_id": metadata["chat_id"],
  1257. },
  1258. user,
  1259. )
  1260. if res and isinstance(res, dict):
  1261. if len(res.get("choices", [])) == 1:
  1262. tags_string = (
  1263. res.get("choices", [])[0]
  1264. .get("message", {})
  1265. .get("content", "")
  1266. )
  1267. else:
  1268. tags_string = ""
  1269. tags_string = tags_string[
  1270. tags_string.find("{") : tags_string.rfind("}") + 1
  1271. ]
  1272. try:
  1273. tags = json.loads(tags_string).get("tags", [])
  1274. Chats.update_chat_tags_by_id(
  1275. metadata["chat_id"], tags, user
  1276. )
  1277. await event_emitter(
  1278. {
  1279. "type": "chat:tags",
  1280. "data": tags,
  1281. }
  1282. )
  1283. except Exception as e:
  1284. pass
  1285. event_emitter = None
  1286. event_caller = None
  1287. if (
  1288. "session_id" in metadata
  1289. and metadata["session_id"]
  1290. and "chat_id" in metadata
  1291. and metadata["chat_id"]
  1292. and "message_id" in metadata
  1293. and metadata["message_id"]
  1294. ):
  1295. event_emitter = get_event_emitter(metadata)
  1296. event_caller = get_event_call(metadata)
  1297. # Non-streaming response
  1298. if not isinstance(response, StreamingResponse):
  1299. if event_emitter:
  1300. try:
  1301. if isinstance(response, dict) or isinstance(response, JSONResponse):
  1302. if isinstance(response, list) and len(response) == 1:
  1303. # If the response is a single-item list, unwrap it #17213
  1304. response = response[0]
  1305. if isinstance(response, JSONResponse) and isinstance(
  1306. response.body, bytes
  1307. ):
  1308. try:
  1309. response_data = json.loads(response.body.decode("utf-8"))
  1310. except json.JSONDecodeError:
  1311. response_data = {
  1312. "error": {"detail": "Invalid JSON response"}
  1313. }
  1314. else:
  1315. response_data = response
  1316. if "error" in response_data:
  1317. error = response_data.get("error")
  1318. if isinstance(error, dict):
  1319. error = error.get("detail", error)
  1320. else:
  1321. error = str(error)
  1322. Chats.upsert_message_to_chat_by_id_and_message_id(
  1323. metadata["chat_id"],
  1324. metadata["message_id"],
  1325. {
  1326. "error": {"content": error},
  1327. },
  1328. )
  1329. if isinstance(error, str) or isinstance(error, dict):
  1330. await event_emitter(
  1331. {
  1332. "type": "chat:message:error",
  1333. "data": {"error": {"content": error}},
  1334. }
  1335. )
  1336. if "selected_model_id" in response_data:
  1337. Chats.upsert_message_to_chat_by_id_and_message_id(
  1338. metadata["chat_id"],
  1339. metadata["message_id"],
  1340. {
  1341. "selectedModelId": response_data["selected_model_id"],
  1342. },
  1343. )
  1344. choices = response_data.get("choices", [])
  1345. if choices and choices[0].get("message", {}).get("content"):
  1346. content = response_data["choices"][0]["message"]["content"]
  1347. if content:
  1348. await event_emitter(
  1349. {
  1350. "type": "chat:completion",
  1351. "data": response_data,
  1352. }
  1353. )
  1354. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1355. await event_emitter(
  1356. {
  1357. "type": "chat:completion",
  1358. "data": {
  1359. "done": True,
  1360. "content": content,
  1361. "title": title,
  1362. },
  1363. }
  1364. )
  1365. # Save message in the database
  1366. Chats.upsert_message_to_chat_by_id_and_message_id(
  1367. metadata["chat_id"],
  1368. metadata["message_id"],
  1369. {
  1370. "role": "assistant",
  1371. "content": content,
  1372. },
  1373. )
  1374. # Send a webhook notification if the user is not active
  1375. if not get_active_status_by_user_id(user.id):
  1376. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1377. if webhook_url:
  1378. await post_webhook(
  1379. request.app.state.WEBUI_NAME,
  1380. webhook_url,
  1381. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1382. {
  1383. "action": "chat",
  1384. "message": content,
  1385. "title": title,
  1386. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1387. },
  1388. )
  1389. await background_tasks_handler()
  1390. if events and isinstance(events, list):
  1391. extra_response = {}
  1392. for event in events:
  1393. if isinstance(event, dict):
  1394. extra_response.update(event)
  1395. else:
  1396. extra_response[event] = True
  1397. response_data = {
  1398. **extra_response,
  1399. **response_data,
  1400. }
  1401. if isinstance(response, dict):
  1402. response = response_data
  1403. if isinstance(response, JSONResponse):
  1404. response = JSONResponse(
  1405. content=response_data,
  1406. headers=response.headers,
  1407. status_code=response.status_code,
  1408. )
  1409. except Exception as e:
  1410. log.debug(f"Error occurred while processing request: {e}")
  1411. pass
  1412. return response
  1413. else:
  1414. if events and isinstance(events, list) and isinstance(response, dict):
  1415. extra_response = {}
  1416. for event in events:
  1417. if isinstance(event, dict):
  1418. extra_response.update(event)
  1419. else:
  1420. extra_response[event] = True
  1421. response = {
  1422. **extra_response,
  1423. **response,
  1424. }
  1425. return response
  1426. # Non standard response
  1427. if not any(
  1428. content_type in response.headers["Content-Type"]
  1429. for content_type in ["text/event-stream", "application/x-ndjson"]
  1430. ):
  1431. return response
  1432. oauth_token = None
  1433. try:
  1434. if request.cookies.get("oauth_session_id", None):
  1435. oauth_token = await request.app.state.oauth_manager.get_oauth_token(
  1436. user.id,
  1437. request.cookies.get("oauth_session_id", None),
  1438. )
  1439. except Exception as e:
  1440. log.error(f"Error getting OAuth token: {e}")
  1441. extra_params = {
  1442. "__event_emitter__": event_emitter,
  1443. "__event_call__": event_caller,
  1444. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  1445. "__metadata__": metadata,
  1446. "__oauth_token__": oauth_token,
  1447. "__request__": request,
  1448. "__model__": model,
  1449. }
  1450. filter_functions = [
  1451. Functions.get_function_by_id(filter_id)
  1452. for filter_id in get_sorted_filter_ids(
  1453. request, model, metadata.get("filter_ids", [])
  1454. )
  1455. ]
  1456. # Streaming response
  1457. if event_emitter and event_caller:
  1458. task_id = str(uuid4()) # Create a unique task ID.
  1459. model_id = form_data.get("model", "")
  1460. def split_content_and_whitespace(content):
  1461. content_stripped = content.rstrip()
  1462. original_whitespace = (
  1463. content[len(content_stripped) :]
  1464. if len(content) > len(content_stripped)
  1465. else ""
  1466. )
  1467. return content_stripped, original_whitespace
  1468. def is_opening_code_block(content):
  1469. backtick_segments = content.split("```")
  1470. # Even number of segments means the last backticks are opening a new block
  1471. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  1472. # Handle as a background task
  1473. async def response_handler(response, events):
  1474. def serialize_content_blocks(content_blocks, raw=False):
  1475. content = ""
  1476. for block in content_blocks:
  1477. if block["type"] == "text":
  1478. block_content = block["content"].strip()
  1479. if block_content:
  1480. content = f"{content}{block_content}\n"
  1481. elif block["type"] == "tool_calls":
  1482. attributes = block.get("attributes", {})
  1483. tool_calls = block.get("content", [])
  1484. results = block.get("results", [])
  1485. if content and not content.endswith("\n"):
  1486. content += "\n"
  1487. if results:
  1488. tool_calls_display_content = ""
  1489. for tool_call in tool_calls:
  1490. tool_call_id = tool_call.get("id", "")
  1491. tool_name = tool_call.get("function", {}).get(
  1492. "name", ""
  1493. )
  1494. tool_arguments = tool_call.get("function", {}).get(
  1495. "arguments", ""
  1496. )
  1497. tool_result = None
  1498. tool_result_files = None
  1499. for result in results:
  1500. if tool_call_id == result.get("tool_call_id", ""):
  1501. tool_result = result.get("content", None)
  1502. tool_result_files = result.get("files", None)
  1503. break
  1504. if tool_result is not None:
  1505. tool_result_embeds = result.get("embeds", "")
  1506. tool_calls_display_content = f'{tool_calls_display_content}<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, ensure_ascii=False))}" files="{html.escape(json.dumps(tool_result_files)) if tool_result_files else ""}" embeds="{html.escape(json.dumps(tool_result_embeds))}">\n<summary>Tool Executed</summary>\n</details>\n'
  1507. else:
  1508. tool_calls_display_content = f'{tool_calls_display_content}<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>\n'
  1509. if not raw:
  1510. content = f"{content}{tool_calls_display_content}"
  1511. else:
  1512. tool_calls_display_content = ""
  1513. for tool_call in tool_calls:
  1514. tool_call_id = tool_call.get("id", "")
  1515. tool_name = tool_call.get("function", {}).get(
  1516. "name", ""
  1517. )
  1518. tool_arguments = tool_call.get("function", {}).get(
  1519. "arguments", ""
  1520. )
  1521. 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>\n'
  1522. if not raw:
  1523. content = f"{content}{tool_calls_display_content}"
  1524. elif block["type"] == "reasoning":
  1525. reasoning_display_content = "\n".join(
  1526. (f"> {line}" if not line.startswith(">") else line)
  1527. for line in block["content"].splitlines()
  1528. )
  1529. reasoning_duration = block.get("duration", None)
  1530. start_tag = block.get("start_tag", "")
  1531. end_tag = block.get("end_tag", "")
  1532. if content and not content.endswith("\n"):
  1533. content += "\n"
  1534. if reasoning_duration is not None:
  1535. if raw:
  1536. content = (
  1537. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1538. )
  1539. else:
  1540. 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'
  1541. else:
  1542. if raw:
  1543. content = (
  1544. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1545. )
  1546. else:
  1547. content = f'{content}<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1548. elif block["type"] == "code_interpreter":
  1549. attributes = block.get("attributes", {})
  1550. output = block.get("output", None)
  1551. lang = attributes.get("lang", "")
  1552. content_stripped, original_whitespace = (
  1553. split_content_and_whitespace(content)
  1554. )
  1555. if is_opening_code_block(content_stripped):
  1556. # Remove trailing backticks that would open a new block
  1557. content = (
  1558. content_stripped.rstrip("`").rstrip()
  1559. + original_whitespace
  1560. )
  1561. else:
  1562. # Keep content as is - either closing backticks or no backticks
  1563. content = content_stripped + original_whitespace
  1564. if content and not content.endswith("\n"):
  1565. content += "\n"
  1566. if output:
  1567. output = html.escape(json.dumps(output))
  1568. if raw:
  1569. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1570. else:
  1571. content = f'{content}<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1572. else:
  1573. if raw:
  1574. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1575. else:
  1576. content = f'{content}<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1577. else:
  1578. block_content = str(block["content"]).strip()
  1579. if block_content:
  1580. content = f"{content}{block['type']}: {block_content}\n"
  1581. return content.strip()
  1582. def convert_content_blocks_to_messages(content_blocks, raw=False):
  1583. messages = []
  1584. temp_blocks = []
  1585. for idx, block in enumerate(content_blocks):
  1586. if block["type"] == "tool_calls":
  1587. messages.append(
  1588. {
  1589. "role": "assistant",
  1590. "content": serialize_content_blocks(temp_blocks, raw),
  1591. "tool_calls": block.get("content"),
  1592. }
  1593. )
  1594. results = block.get("results", [])
  1595. for result in results:
  1596. messages.append(
  1597. {
  1598. "role": "tool",
  1599. "tool_call_id": result["tool_call_id"],
  1600. "content": result.get("content", "") or "",
  1601. }
  1602. )
  1603. temp_blocks = []
  1604. else:
  1605. temp_blocks.append(block)
  1606. if temp_blocks:
  1607. content = serialize_content_blocks(temp_blocks, raw)
  1608. if content:
  1609. messages.append(
  1610. {
  1611. "role": "assistant",
  1612. "content": content,
  1613. }
  1614. )
  1615. return messages
  1616. def tag_content_handler(content_type, tags, content, content_blocks):
  1617. end_flag = False
  1618. def extract_attributes(tag_content):
  1619. """Extract attributes from a tag if they exist."""
  1620. attributes = {}
  1621. if not tag_content: # Ensure tag_content is not None
  1622. return attributes
  1623. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1624. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1625. for key, value in matches:
  1626. attributes[key] = value
  1627. return attributes
  1628. if content_blocks[-1]["type"] == "text":
  1629. for start_tag, end_tag in tags:
  1630. start_tag_pattern = rf"{re.escape(start_tag)}"
  1631. if start_tag.startswith("<") and start_tag.endswith(">"):
  1632. # Match start tag e.g., <tag> or <tag attr="value">
  1633. # remove both '<' and '>' from start_tag
  1634. # Match start tag with attributes
  1635. start_tag_pattern = (
  1636. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1637. )
  1638. match = re.search(start_tag_pattern, content)
  1639. if match:
  1640. try:
  1641. attr_content = (
  1642. match.group(1) if match.group(1) else ""
  1643. ) # Ensure it's not None
  1644. except:
  1645. attr_content = ""
  1646. attributes = extract_attributes(
  1647. attr_content
  1648. ) # Extract attributes safely
  1649. # Capture everything before and after the matched tag
  1650. before_tag = content[
  1651. : match.start()
  1652. ] # Content before opening tag
  1653. after_tag = content[
  1654. match.end() :
  1655. ] # Content after opening tag
  1656. # Remove the start tag and after from the currently handling text block
  1657. content_blocks[-1]["content"] = content_blocks[-1][
  1658. "content"
  1659. ].replace(match.group(0) + after_tag, "")
  1660. if before_tag:
  1661. content_blocks[-1]["content"] = before_tag
  1662. if not content_blocks[-1]["content"]:
  1663. content_blocks.pop()
  1664. # Append the new block
  1665. content_blocks.append(
  1666. {
  1667. "type": content_type,
  1668. "start_tag": start_tag,
  1669. "end_tag": end_tag,
  1670. "attributes": attributes,
  1671. "content": "",
  1672. "started_at": time.time(),
  1673. }
  1674. )
  1675. if after_tag:
  1676. content_blocks[-1]["content"] = after_tag
  1677. tag_content_handler(
  1678. content_type, tags, after_tag, content_blocks
  1679. )
  1680. break
  1681. elif content_blocks[-1]["type"] == content_type:
  1682. start_tag = content_blocks[-1]["start_tag"]
  1683. end_tag = content_blocks[-1]["end_tag"]
  1684. if end_tag.startswith("<") and end_tag.endswith(">"):
  1685. # Match end tag e.g., </tag>
  1686. end_tag_pattern = rf"{re.escape(end_tag)}"
  1687. else:
  1688. # Handle cases where end_tag is just a tag name
  1689. end_tag_pattern = rf"{re.escape(end_tag)}"
  1690. # Check if the content has the end tag
  1691. if re.search(end_tag_pattern, content):
  1692. end_flag = True
  1693. block_content = content_blocks[-1]["content"]
  1694. # Strip start and end tags from the content
  1695. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1696. block_content = re.sub(
  1697. start_tag_pattern, "", block_content
  1698. ).strip()
  1699. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1700. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1701. # Content inside the tag
  1702. block_content = (
  1703. split_content[0].strip() if split_content else ""
  1704. )
  1705. # Leftover content (everything after `</tag>`)
  1706. leftover_content = (
  1707. split_content[1].strip() if len(split_content) > 1 else ""
  1708. )
  1709. if block_content:
  1710. content_blocks[-1]["content"] = block_content
  1711. content_blocks[-1]["ended_at"] = time.time()
  1712. content_blocks[-1]["duration"] = int(
  1713. content_blocks[-1]["ended_at"]
  1714. - content_blocks[-1]["started_at"]
  1715. )
  1716. # Reset the content_blocks by appending a new text block
  1717. if content_type != "code_interpreter":
  1718. if leftover_content:
  1719. content_blocks.append(
  1720. {
  1721. "type": "text",
  1722. "content": leftover_content,
  1723. }
  1724. )
  1725. else:
  1726. content_blocks.append(
  1727. {
  1728. "type": "text",
  1729. "content": "",
  1730. }
  1731. )
  1732. else:
  1733. # Remove the block if content is empty
  1734. content_blocks.pop()
  1735. if leftover_content:
  1736. content_blocks.append(
  1737. {
  1738. "type": "text",
  1739. "content": leftover_content,
  1740. }
  1741. )
  1742. else:
  1743. content_blocks.append(
  1744. {
  1745. "type": "text",
  1746. "content": "",
  1747. }
  1748. )
  1749. # Clean processed content
  1750. start_tag_pattern = rf"{re.escape(start_tag)}"
  1751. if start_tag.startswith("<") and start_tag.endswith(">"):
  1752. # Match start tag e.g., <tag> or <tag attr="value">
  1753. # remove both '<' and '>' from start_tag
  1754. # Match start tag with attributes
  1755. start_tag_pattern = (
  1756. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1757. )
  1758. content = re.sub(
  1759. rf"{start_tag_pattern}(.|\n)*?{re.escape(end_tag)}",
  1760. "",
  1761. content,
  1762. flags=re.DOTALL,
  1763. )
  1764. return content, content_blocks, end_flag
  1765. message = Chats.get_message_by_id_and_message_id(
  1766. metadata["chat_id"], metadata["message_id"]
  1767. )
  1768. tool_calls = []
  1769. last_assistant_message = None
  1770. try:
  1771. if form_data["messages"][-1]["role"] == "assistant":
  1772. last_assistant_message = get_last_assistant_message(
  1773. form_data["messages"]
  1774. )
  1775. except Exception as e:
  1776. pass
  1777. content = (
  1778. message.get("content", "")
  1779. if message
  1780. else last_assistant_message if last_assistant_message else ""
  1781. )
  1782. content_blocks = [
  1783. {
  1784. "type": "text",
  1785. "content": content,
  1786. }
  1787. ]
  1788. reasoning_tags_param = metadata.get("params", {}).get("reasoning_tags")
  1789. DETECT_REASONING_TAGS = reasoning_tags_param is not False
  1790. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1791. "code_interpreter", False
  1792. )
  1793. reasoning_tags = []
  1794. if DETECT_REASONING_TAGS:
  1795. if (
  1796. isinstance(reasoning_tags_param, list)
  1797. and len(reasoning_tags_param) == 2
  1798. ):
  1799. reasoning_tags = [
  1800. (reasoning_tags_param[0], reasoning_tags_param[1])
  1801. ]
  1802. else:
  1803. reasoning_tags = DEFAULT_REASONING_TAGS
  1804. try:
  1805. for event in events:
  1806. await event_emitter(
  1807. {
  1808. "type": "chat:completion",
  1809. "data": event,
  1810. }
  1811. )
  1812. # Save message in the database
  1813. Chats.upsert_message_to_chat_by_id_and_message_id(
  1814. metadata["chat_id"],
  1815. metadata["message_id"],
  1816. {
  1817. **event,
  1818. },
  1819. )
  1820. async def stream_body_handler(response, form_data):
  1821. nonlocal content
  1822. nonlocal content_blocks
  1823. response_tool_calls = []
  1824. delta_count = 0
  1825. delta_chunk_size = max(
  1826. CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
  1827. int(
  1828. metadata.get("params", {}).get("stream_delta_chunk_size")
  1829. or 1
  1830. ),
  1831. )
  1832. last_delta_data = None
  1833. async def flush_pending_delta_data(threshold: int = 0):
  1834. nonlocal delta_count
  1835. nonlocal last_delta_data
  1836. if delta_count >= threshold and last_delta_data:
  1837. await event_emitter(
  1838. {
  1839. "type": "chat:completion",
  1840. "data": last_delta_data,
  1841. }
  1842. )
  1843. delta_count = 0
  1844. last_delta_data = None
  1845. async for line in response.body_iterator:
  1846. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1847. data = line
  1848. # Skip empty lines
  1849. if not data.strip():
  1850. continue
  1851. # "data:" is the prefix for each event
  1852. if not data.startswith("data:"):
  1853. continue
  1854. # Remove the prefix
  1855. data = data[len("data:") :].strip()
  1856. try:
  1857. data = json.loads(data)
  1858. data, _ = await process_filter_functions(
  1859. request=request,
  1860. filter_functions=filter_functions,
  1861. filter_type="stream",
  1862. form_data=data,
  1863. extra_params={"__body__": form_data, **extra_params},
  1864. )
  1865. if data:
  1866. if "event" in data:
  1867. await event_emitter(data.get("event", {}))
  1868. if "selected_model_id" in data:
  1869. model_id = data["selected_model_id"]
  1870. Chats.upsert_message_to_chat_by_id_and_message_id(
  1871. metadata["chat_id"],
  1872. metadata["message_id"],
  1873. {
  1874. "selectedModelId": model_id,
  1875. },
  1876. )
  1877. await event_emitter(
  1878. {
  1879. "type": "chat:completion",
  1880. "data": data,
  1881. }
  1882. )
  1883. else:
  1884. choices = data.get("choices", [])
  1885. # 17421
  1886. usage = data.get("usage", {}) or {}
  1887. usage.update(data.get("timings", {})) # llama.cpp
  1888. if usage:
  1889. await event_emitter(
  1890. {
  1891. "type": "chat:completion",
  1892. "data": {
  1893. "usage": usage,
  1894. },
  1895. }
  1896. )
  1897. if not choices:
  1898. error = data.get("error", {})
  1899. if error:
  1900. await event_emitter(
  1901. {
  1902. "type": "chat:completion",
  1903. "data": {
  1904. "error": error,
  1905. },
  1906. }
  1907. )
  1908. continue
  1909. delta = choices[0].get("delta", {})
  1910. delta_tool_calls = delta.get("tool_calls", None)
  1911. if delta_tool_calls:
  1912. for delta_tool_call in delta_tool_calls:
  1913. tool_call_index = delta_tool_call.get(
  1914. "index"
  1915. )
  1916. if tool_call_index is not None:
  1917. # Check if the tool call already exists
  1918. current_response_tool_call = None
  1919. for (
  1920. response_tool_call
  1921. ) in response_tool_calls:
  1922. if (
  1923. response_tool_call.get("index")
  1924. == tool_call_index
  1925. ):
  1926. current_response_tool_call = (
  1927. response_tool_call
  1928. )
  1929. break
  1930. if current_response_tool_call is None:
  1931. # Add the new tool call
  1932. delta_tool_call.setdefault(
  1933. "function", {}
  1934. )
  1935. delta_tool_call[
  1936. "function"
  1937. ].setdefault("name", "")
  1938. delta_tool_call[
  1939. "function"
  1940. ].setdefault("arguments", "")
  1941. response_tool_calls.append(
  1942. delta_tool_call
  1943. )
  1944. else:
  1945. # Update the existing tool call
  1946. delta_name = delta_tool_call.get(
  1947. "function", {}
  1948. ).get("name")
  1949. delta_arguments = (
  1950. delta_tool_call.get(
  1951. "function", {}
  1952. ).get("arguments")
  1953. )
  1954. if delta_name:
  1955. current_response_tool_call[
  1956. "function"
  1957. ]["name"] += delta_name
  1958. if delta_arguments:
  1959. current_response_tool_call[
  1960. "function"
  1961. ][
  1962. "arguments"
  1963. ] += delta_arguments
  1964. value = delta.get("content")
  1965. reasoning_content = (
  1966. delta.get("reasoning_content")
  1967. or delta.get("reasoning")
  1968. or delta.get("thinking")
  1969. )
  1970. if reasoning_content:
  1971. if (
  1972. not content_blocks
  1973. or content_blocks[-1]["type"] != "reasoning"
  1974. ):
  1975. reasoning_block = {
  1976. "type": "reasoning",
  1977. "start_tag": "<think>",
  1978. "end_tag": "</think>",
  1979. "attributes": {
  1980. "type": "reasoning_content"
  1981. },
  1982. "content": "",
  1983. "started_at": time.time(),
  1984. }
  1985. content_blocks.append(reasoning_block)
  1986. else:
  1987. reasoning_block = content_blocks[-1]
  1988. reasoning_block["content"] += reasoning_content
  1989. data = {
  1990. "content": serialize_content_blocks(
  1991. content_blocks
  1992. )
  1993. }
  1994. if value:
  1995. if (
  1996. content_blocks
  1997. and content_blocks[-1]["type"]
  1998. == "reasoning"
  1999. and content_blocks[-1]
  2000. .get("attributes", {})
  2001. .get("type")
  2002. == "reasoning_content"
  2003. ):
  2004. reasoning_block = content_blocks[-1]
  2005. reasoning_block["ended_at"] = time.time()
  2006. reasoning_block["duration"] = int(
  2007. reasoning_block["ended_at"]
  2008. - reasoning_block["started_at"]
  2009. )
  2010. content_blocks.append(
  2011. {
  2012. "type": "text",
  2013. "content": "",
  2014. }
  2015. )
  2016. content = f"{content}{value}"
  2017. if not content_blocks:
  2018. content_blocks.append(
  2019. {
  2020. "type": "text",
  2021. "content": "",
  2022. }
  2023. )
  2024. content_blocks[-1]["content"] = (
  2025. content_blocks[-1]["content"] + value
  2026. )
  2027. if DETECT_REASONING_TAGS:
  2028. content, content_blocks, _ = (
  2029. tag_content_handler(
  2030. "reasoning",
  2031. reasoning_tags,
  2032. content,
  2033. content_blocks,
  2034. )
  2035. )
  2036. content, content_blocks, _ = (
  2037. tag_content_handler(
  2038. "solution",
  2039. DEFAULT_SOLUTION_TAGS,
  2040. content,
  2041. content_blocks,
  2042. )
  2043. )
  2044. if DETECT_CODE_INTERPRETER:
  2045. content, content_blocks, end = (
  2046. tag_content_handler(
  2047. "code_interpreter",
  2048. DEFAULT_CODE_INTERPRETER_TAGS,
  2049. content,
  2050. content_blocks,
  2051. )
  2052. )
  2053. if end:
  2054. break
  2055. if ENABLE_REALTIME_CHAT_SAVE:
  2056. # Save message in the database
  2057. Chats.upsert_message_to_chat_by_id_and_message_id(
  2058. metadata["chat_id"],
  2059. metadata["message_id"],
  2060. {
  2061. "content": serialize_content_blocks(
  2062. content_blocks
  2063. ),
  2064. },
  2065. )
  2066. else:
  2067. data = {
  2068. "content": serialize_content_blocks(
  2069. content_blocks
  2070. ),
  2071. }
  2072. if delta:
  2073. delta_count += 1
  2074. last_delta_data = data
  2075. if delta_count >= delta_chunk_size:
  2076. await flush_pending_delta_data(delta_chunk_size)
  2077. else:
  2078. await event_emitter(
  2079. {
  2080. "type": "chat:completion",
  2081. "data": data,
  2082. }
  2083. )
  2084. except Exception as e:
  2085. done = "data: [DONE]" in line
  2086. if done:
  2087. pass
  2088. else:
  2089. log.debug(f"Error: {e}")
  2090. continue
  2091. await flush_pending_delta_data()
  2092. if content_blocks:
  2093. # Clean up the last text block
  2094. if content_blocks[-1]["type"] == "text":
  2095. content_blocks[-1]["content"] = content_blocks[-1][
  2096. "content"
  2097. ].strip()
  2098. if not content_blocks[-1]["content"]:
  2099. content_blocks.pop()
  2100. if not content_blocks:
  2101. content_blocks.append(
  2102. {
  2103. "type": "text",
  2104. "content": "",
  2105. }
  2106. )
  2107. if content_blocks[-1]["type"] == "reasoning":
  2108. reasoning_block = content_blocks[-1]
  2109. if reasoning_block.get("ended_at") is None:
  2110. reasoning_block["ended_at"] = time.time()
  2111. reasoning_block["duration"] = int(
  2112. reasoning_block["ended_at"]
  2113. - reasoning_block["started_at"]
  2114. )
  2115. if response_tool_calls:
  2116. tool_calls.append(response_tool_calls)
  2117. if response.background:
  2118. await response.background()
  2119. await stream_body_handler(response, form_data)
  2120. tool_call_retries = 0
  2121. while (
  2122. len(tool_calls) > 0
  2123. and tool_call_retries < CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES
  2124. ):
  2125. tool_call_retries += 1
  2126. response_tool_calls = tool_calls.pop(0)
  2127. content_blocks.append(
  2128. {
  2129. "type": "tool_calls",
  2130. "content": response_tool_calls,
  2131. }
  2132. )
  2133. await event_emitter(
  2134. {
  2135. "type": "chat:completion",
  2136. "data": {
  2137. "content": serialize_content_blocks(content_blocks),
  2138. },
  2139. }
  2140. )
  2141. tools = metadata.get("tools", {})
  2142. results = []
  2143. for tool_call in response_tool_calls:
  2144. print("tool_call", tool_call)
  2145. tool_call_id = tool_call.get("id", "")
  2146. tool_name = tool_call.get("function", {}).get("name", "")
  2147. tool_args = tool_call.get("function", {}).get("arguments", "{}")
  2148. tool_function_params = {}
  2149. try:
  2150. # json.loads cannot be used because some models do not produce valid JSON
  2151. tool_function_params = ast.literal_eval(tool_args)
  2152. except Exception as e:
  2153. log.debug(e)
  2154. # Fallback to JSON parsing
  2155. try:
  2156. tool_function_params = json.loads(tool_args)
  2157. except Exception as e:
  2158. log.error(
  2159. f"Error parsing tool call arguments: {tool_args}"
  2160. )
  2161. # Mutate the original tool call response params as they are passed back to the passed
  2162. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  2163. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  2164. # params are not valid json.
  2165. # Main case so far is no args = "" = invalid json.
  2166. log.debug(
  2167. f"Parsed args from {tool_args} to {tool_function_params}"
  2168. )
  2169. tool_call.setdefault("function", {})["arguments"] = json.dumps(
  2170. tool_function_params
  2171. )
  2172. tool_result = None
  2173. if tool_name in tools:
  2174. tool = tools[tool_name]
  2175. spec = tool.get("spec", {})
  2176. try:
  2177. allowed_params = (
  2178. spec.get("parameters", {})
  2179. .get("properties", {})
  2180. .keys()
  2181. )
  2182. tool_function_params = {
  2183. k: v
  2184. for k, v in tool_function_params.items()
  2185. if k in allowed_params
  2186. }
  2187. if tool.get("direct", False):
  2188. tool_result = await event_caller(
  2189. {
  2190. "type": "execute:tool",
  2191. "data": {
  2192. "id": str(uuid4()),
  2193. "name": tool_name,
  2194. "params": tool_function_params,
  2195. "server": tool.get("server", {}),
  2196. "session_id": metadata.get(
  2197. "session_id", None
  2198. ),
  2199. },
  2200. }
  2201. )
  2202. else:
  2203. tool_function = tool["callable"]
  2204. tool_result = await tool_function(
  2205. **tool_function_params
  2206. )
  2207. except Exception as e:
  2208. tool_result = str(e)
  2209. tool_result_embeds = []
  2210. if isinstance(tool_result, HTMLResponse):
  2211. content_disposition = tool_result.headers.get(
  2212. "Content-Disposition", ""
  2213. )
  2214. if "inline" in content_disposition:
  2215. content = tool_result.body.decode("utf-8")
  2216. tool_result_embeds.append(content)
  2217. if 200 <= tool_result.status_code < 300:
  2218. tool_result = {
  2219. "status": "success",
  2220. "code": "ui_component",
  2221. "message": "Embedded UI result is active and visible to the user.",
  2222. }
  2223. elif 400 <= tool_result.status_code < 500:
  2224. tool_result = {
  2225. "status": "error",
  2226. "code": "ui_component",
  2227. "message": f"Client error {tool_result.status_code} from embedded UI result.",
  2228. }
  2229. elif 500 <= tool_result.status_code < 600:
  2230. tool_result = {
  2231. "status": "error",
  2232. "code": "ui_component",
  2233. "message": f"Server error {tool_result.status_code} from embedded UI result.",
  2234. }
  2235. else:
  2236. tool_result = {
  2237. "status": "error",
  2238. "code": "ui_component",
  2239. "message": f"Unexpected status code {tool_result.status_code} from embedded UI result.",
  2240. }
  2241. else:
  2242. tool_result = tool_result.body.decode("utf-8")
  2243. elif (
  2244. tool.get("type") == "external"
  2245. and isinstance(tool_result, tuple)
  2246. ) or (
  2247. tool.get("direct", True)
  2248. and isinstance(tool_result, list)
  2249. and len(tool_result) == 2
  2250. ):
  2251. tool_result, tool_response_headers = tool_result
  2252. if tool_response_headers and isinstance(
  2253. tool_response_headers, dict
  2254. ):
  2255. content_disposition = tool_response_headers.get(
  2256. "Content-Disposition",
  2257. tool_response_headers.get(
  2258. "content-disposition", ""
  2259. ),
  2260. )
  2261. if "inline" in content_disposition:
  2262. content_type = tool_response_headers.get(
  2263. "Content-Type",
  2264. tool_response_headers.get("content-type", ""),
  2265. )
  2266. location = tool_response_headers.get(
  2267. "Location",
  2268. tool_response_headers.get("location", ""),
  2269. )
  2270. if "text/html" in content_type:
  2271. # Display as iframe embed
  2272. tool_result_embeds.append(tool_result)
  2273. tool_result = {
  2274. "status": "success",
  2275. "code": "ui_component",
  2276. "message": "Embedded UI result is active and visible to the user.",
  2277. }
  2278. elif location:
  2279. tool_result_embeds.append(location)
  2280. tool_result = {
  2281. "status": "success",
  2282. "code": "ui_component",
  2283. "message": "Embedded UI result is active and visible to the user.",
  2284. }
  2285. tool_result_files = []
  2286. if isinstance(tool_result, list):
  2287. for item in tool_result:
  2288. # check if string
  2289. if isinstance(item, str) and item.startswith("data:"):
  2290. tool_result_files.append(
  2291. {
  2292. "type": "data",
  2293. "content": item,
  2294. }
  2295. )
  2296. tool_result.remove(item)
  2297. if tool.get("type") == "mcp":
  2298. if isinstance(item, dict):
  2299. if (
  2300. item.get("type") == "image"
  2301. or item.get("type") == "audio"
  2302. ):
  2303. file_url = get_file_url_from_base64(
  2304. request,
  2305. f"data:{item.get('mimeType')};base64,{item.get('data', item.get('blob', ''))}",
  2306. {
  2307. "chat_id": metadata.get(
  2308. "chat_id", None
  2309. ),
  2310. "message_id": metadata.get(
  2311. "message_id", None
  2312. ),
  2313. "session_id": metadata.get(
  2314. "session_id", None
  2315. ),
  2316. "result": item,
  2317. },
  2318. user,
  2319. )
  2320. tool_result_files.append(
  2321. {
  2322. "type": item.get("type", "data"),
  2323. "url": file_url,
  2324. }
  2325. )
  2326. tool_result.remove(item)
  2327. if tool_result_files:
  2328. if not isinstance(tool_result, list):
  2329. tool_result = [
  2330. tool_result,
  2331. ]
  2332. for file in tool_result_files:
  2333. tool_result.append(
  2334. {
  2335. "type": file.get("type", "data"),
  2336. "content": "Result is being displayed as a file.",
  2337. }
  2338. )
  2339. if isinstance(tool_result, dict) or isinstance(
  2340. tool_result, list
  2341. ):
  2342. tool_result = json.dumps(
  2343. tool_result, indent=2, ensure_ascii=False
  2344. )
  2345. results.append(
  2346. {
  2347. "tool_call_id": tool_call_id,
  2348. "content": tool_result or "",
  2349. **(
  2350. {"files": tool_result_files}
  2351. if tool_result_files
  2352. else {}
  2353. ),
  2354. **(
  2355. {"embeds": tool_result_embeds}
  2356. if tool_result_embeds
  2357. else {}
  2358. ),
  2359. }
  2360. )
  2361. content_blocks[-1]["results"] = results
  2362. content_blocks.append(
  2363. {
  2364. "type": "text",
  2365. "content": "",
  2366. }
  2367. )
  2368. await event_emitter(
  2369. {
  2370. "type": "chat:completion",
  2371. "data": {
  2372. "content": serialize_content_blocks(content_blocks),
  2373. },
  2374. }
  2375. )
  2376. try:
  2377. new_form_data = {
  2378. "model": model_id,
  2379. "stream": True,
  2380. "tools": form_data["tools"],
  2381. "messages": [
  2382. *form_data["messages"],
  2383. *convert_content_blocks_to_messages(
  2384. content_blocks, True
  2385. ),
  2386. ],
  2387. }
  2388. res = await generate_chat_completion(
  2389. request,
  2390. new_form_data,
  2391. user,
  2392. )
  2393. if isinstance(res, StreamingResponse):
  2394. await stream_body_handler(res, new_form_data)
  2395. else:
  2396. break
  2397. except Exception as e:
  2398. log.debug(e)
  2399. break
  2400. if DETECT_CODE_INTERPRETER:
  2401. MAX_RETRIES = 5
  2402. retries = 0
  2403. while (
  2404. content_blocks[-1]["type"] == "code_interpreter"
  2405. and retries < MAX_RETRIES
  2406. ):
  2407. await event_emitter(
  2408. {
  2409. "type": "chat:completion",
  2410. "data": {
  2411. "content": serialize_content_blocks(content_blocks),
  2412. },
  2413. }
  2414. )
  2415. retries += 1
  2416. log.debug(f"Attempt count: {retries}")
  2417. output = ""
  2418. try:
  2419. if content_blocks[-1]["attributes"].get("type") == "code":
  2420. code = content_blocks[-1]["content"]
  2421. if CODE_INTERPRETER_BLOCKED_MODULES:
  2422. blocking_code = textwrap.dedent(
  2423. f"""
  2424. import builtins
  2425. BLOCKED_MODULES = {CODE_INTERPRETER_BLOCKED_MODULES}
  2426. _real_import = builtins.__import__
  2427. def restricted_import(name, globals=None, locals=None, fromlist=(), level=0):
  2428. if name.split('.')[0] in BLOCKED_MODULES:
  2429. importer_name = globals.get('__name__') if globals else None
  2430. if importer_name == '__main__':
  2431. raise ImportError(
  2432. f"Direct import of module {{name}} is restricted."
  2433. )
  2434. return _real_import(name, globals, locals, fromlist, level)
  2435. builtins.__import__ = restricted_import
  2436. """
  2437. )
  2438. code = blocking_code + "\n" + code
  2439. if (
  2440. request.app.state.config.CODE_INTERPRETER_ENGINE
  2441. == "pyodide"
  2442. ):
  2443. output = await event_caller(
  2444. {
  2445. "type": "execute:python",
  2446. "data": {
  2447. "id": str(uuid4()),
  2448. "code": code,
  2449. "session_id": metadata.get(
  2450. "session_id", None
  2451. ),
  2452. },
  2453. }
  2454. )
  2455. elif (
  2456. request.app.state.config.CODE_INTERPRETER_ENGINE
  2457. == "jupyter"
  2458. ):
  2459. output = await execute_code_jupyter(
  2460. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  2461. code,
  2462. (
  2463. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  2464. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2465. == "token"
  2466. else None
  2467. ),
  2468. (
  2469. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  2470. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2471. == "password"
  2472. else None
  2473. ),
  2474. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  2475. )
  2476. else:
  2477. output = {
  2478. "stdout": "Code interpreter engine not configured."
  2479. }
  2480. log.debug(f"Code interpreter output: {output}")
  2481. if isinstance(output, dict):
  2482. stdout = output.get("stdout", "")
  2483. if isinstance(stdout, str):
  2484. stdoutLines = stdout.split("\n")
  2485. for idx, line in enumerate(stdoutLines):
  2486. if "data:image/png;base64" in line:
  2487. image_url = get_image_url_from_base64(
  2488. request,
  2489. line,
  2490. metadata,
  2491. user,
  2492. )
  2493. if image_url:
  2494. stdoutLines[idx] = (
  2495. f"![Output Image]({image_url})"
  2496. )
  2497. output["stdout"] = "\n".join(stdoutLines)
  2498. result = output.get("result", "")
  2499. if isinstance(result, str):
  2500. resultLines = result.split("\n")
  2501. for idx, line in enumerate(resultLines):
  2502. if "data:image/png;base64" in line:
  2503. image_url = get_image_url_from_base64(
  2504. request,
  2505. line,
  2506. metadata,
  2507. user,
  2508. )
  2509. resultLines[idx] = (
  2510. f"![Output Image]({image_url})"
  2511. )
  2512. output["result"] = "\n".join(resultLines)
  2513. except Exception as e:
  2514. output = str(e)
  2515. content_blocks[-1]["output"] = output
  2516. content_blocks.append(
  2517. {
  2518. "type": "text",
  2519. "content": "",
  2520. }
  2521. )
  2522. await event_emitter(
  2523. {
  2524. "type": "chat:completion",
  2525. "data": {
  2526. "content": serialize_content_blocks(content_blocks),
  2527. },
  2528. }
  2529. )
  2530. try:
  2531. new_form_data = {
  2532. "model": model_id,
  2533. "stream": True,
  2534. "messages": [
  2535. *form_data["messages"],
  2536. {
  2537. "role": "assistant",
  2538. "content": serialize_content_blocks(
  2539. content_blocks, raw=True
  2540. ),
  2541. },
  2542. ],
  2543. }
  2544. res = await generate_chat_completion(
  2545. request,
  2546. new_form_data,
  2547. user,
  2548. )
  2549. if isinstance(res, StreamingResponse):
  2550. await stream_body_handler(res, new_form_data)
  2551. else:
  2552. break
  2553. except Exception as e:
  2554. log.debug(e)
  2555. break
  2556. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  2557. data = {
  2558. "done": True,
  2559. "content": serialize_content_blocks(content_blocks),
  2560. "title": title,
  2561. }
  2562. if not ENABLE_REALTIME_CHAT_SAVE:
  2563. # Save message in the database
  2564. Chats.upsert_message_to_chat_by_id_and_message_id(
  2565. metadata["chat_id"],
  2566. metadata["message_id"],
  2567. {
  2568. "content": serialize_content_blocks(content_blocks),
  2569. },
  2570. )
  2571. # Send a webhook notification if the user is not active
  2572. if not get_active_status_by_user_id(user.id):
  2573. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  2574. if webhook_url:
  2575. await post_webhook(
  2576. request.app.state.WEBUI_NAME,
  2577. webhook_url,
  2578. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  2579. {
  2580. "action": "chat",
  2581. "message": content,
  2582. "title": title,
  2583. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  2584. },
  2585. )
  2586. await event_emitter(
  2587. {
  2588. "type": "chat:completion",
  2589. "data": data,
  2590. }
  2591. )
  2592. await background_tasks_handler()
  2593. except asyncio.CancelledError:
  2594. log.warning("Task was cancelled!")
  2595. await event_emitter({"type": "chat:tasks:cancel"})
  2596. if not ENABLE_REALTIME_CHAT_SAVE:
  2597. # Save message in the database
  2598. Chats.upsert_message_to_chat_by_id_and_message_id(
  2599. metadata["chat_id"],
  2600. metadata["message_id"],
  2601. {
  2602. "content": serialize_content_blocks(content_blocks),
  2603. },
  2604. )
  2605. if response.background is not None:
  2606. await response.background()
  2607. return await response_handler(response, events)
  2608. else:
  2609. # Fallback to the original response
  2610. async def stream_wrapper(original_generator, events):
  2611. def wrap_item(item):
  2612. return f"data: {item}\n\n"
  2613. for event in events:
  2614. event, _ = await process_filter_functions(
  2615. request=request,
  2616. filter_functions=filter_functions,
  2617. filter_type="stream",
  2618. form_data=event,
  2619. extra_params=extra_params,
  2620. )
  2621. if event:
  2622. yield wrap_item(json.dumps(event))
  2623. async for data in original_generator:
  2624. data, _ = await process_filter_functions(
  2625. request=request,
  2626. filter_functions=filter_functions,
  2627. filter_type="stream",
  2628. form_data=data,
  2629. extra_params=extra_params,
  2630. )
  2631. if data:
  2632. yield data
  2633. return StreamingResponse(
  2634. stream_wrapper(response.body_iterator, events),
  2635. headers=dict(response.headers),
  2636. background=response.background,
  2637. )