middleware.py 94 KB

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