middleware.py 58 KB

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