middleware.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  1. import time
  2. import logging
  3. import sys
  4. import asyncio
  5. from aiocache import cached
  6. from typing import Any, Optional
  7. import random
  8. import json
  9. import inspect
  10. from uuid import uuid4
  11. from fastapi import Request
  12. from fastapi import BackgroundTasks
  13. from starlette.responses import Response, StreamingResponse
  14. from open_webui.models.chats import Chats
  15. from open_webui.models.users import Users
  16. from open_webui.socket.main import (
  17. get_event_call,
  18. get_event_emitter,
  19. get_user_id_from_session_pool,
  20. )
  21. from open_webui.routers.tasks import (
  22. generate_queries,
  23. generate_title,
  24. generate_chat_tags,
  25. )
  26. from open_webui.utils.webhook import post_webhook
  27. from open_webui.models.users import UserModel
  28. from open_webui.models.functions import Functions
  29. from open_webui.models.models import Models
  30. from open_webui.retrieval.utils import get_sources_from_files
  31. from open_webui.utils.chat import generate_chat_completion
  32. from open_webui.utils.task import (
  33. get_task_model_id,
  34. rag_template,
  35. tools_function_calling_generation_template,
  36. )
  37. from open_webui.utils.misc import (
  38. get_message_list,
  39. add_or_update_system_message,
  40. get_last_user_message,
  41. prepend_to_first_user_message_content,
  42. )
  43. from open_webui.utils.tools import get_tools
  44. from open_webui.utils.plugin import load_function_module_by_id
  45. from open_webui.tasks import create_task
  46. from open_webui.config import DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  47. from open_webui.env import (
  48. SRC_LOG_LEVELS,
  49. GLOBAL_LOG_LEVEL,
  50. BYPASS_MODEL_ACCESS_CONTROL,
  51. WEBUI_URL,
  52. )
  53. from open_webui.constants import TASKS
  54. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  55. log = logging.getLogger(__name__)
  56. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  57. async def chat_completion_filter_functions_handler(request, body, model, extra_params):
  58. skip_files = None
  59. def get_filter_function_ids(model):
  60. def get_priority(function_id):
  61. function = Functions.get_function_by_id(function_id)
  62. if function is not None and hasattr(function, "valves"):
  63. # TODO: Fix FunctionModel
  64. return (function.valves if function.valves else {}).get("priority", 0)
  65. return 0
  66. filter_ids = [
  67. function.id for function in Functions.get_global_filter_functions()
  68. ]
  69. if "info" in model and "meta" in model["info"]:
  70. filter_ids.extend(model["info"]["meta"].get("filterIds", []))
  71. filter_ids = list(set(filter_ids))
  72. enabled_filter_ids = [
  73. function.id
  74. for function in Functions.get_functions_by_type("filter", active_only=True)
  75. ]
  76. filter_ids = [
  77. filter_id for filter_id in filter_ids if filter_id in enabled_filter_ids
  78. ]
  79. filter_ids.sort(key=get_priority)
  80. return filter_ids
  81. filter_ids = get_filter_function_ids(model)
  82. for filter_id in filter_ids:
  83. filter = Functions.get_function_by_id(filter_id)
  84. if not filter:
  85. continue
  86. if filter_id in request.app.state.FUNCTIONS:
  87. function_module = request.app.state.FUNCTIONS[filter_id]
  88. else:
  89. function_module, _, _ = load_function_module_by_id(filter_id)
  90. request.app.state.FUNCTIONS[filter_id] = function_module
  91. # Check if the function has a file_handler variable
  92. if hasattr(function_module, "file_handler"):
  93. skip_files = function_module.file_handler
  94. # Apply valves to the function
  95. if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
  96. valves = Functions.get_function_valves_by_id(filter_id)
  97. function_module.valves = function_module.Valves(
  98. **(valves if valves else {})
  99. )
  100. if hasattr(function_module, "inlet"):
  101. try:
  102. inlet = function_module.inlet
  103. # Create a dictionary of parameters to be passed to the function
  104. params = {"body": body} | {
  105. k: v
  106. for k, v in {
  107. **extra_params,
  108. "__model__": model,
  109. "__id__": filter_id,
  110. }.items()
  111. if k in inspect.signature(inlet).parameters
  112. }
  113. if "__user__" in params and hasattr(function_module, "UserValves"):
  114. try:
  115. params["__user__"]["valves"] = function_module.UserValves(
  116. **Functions.get_user_valves_by_id_and_user_id(
  117. filter_id, params["__user__"]["id"]
  118. )
  119. )
  120. except Exception as e:
  121. print(e)
  122. if inspect.iscoroutinefunction(inlet):
  123. body = await inlet(**params)
  124. else:
  125. body = inlet(**params)
  126. except Exception as e:
  127. print(f"Error: {e}")
  128. raise e
  129. if skip_files and "files" in body.get("metadata", {}):
  130. del body["metadata"]["files"]
  131. return body, {}
  132. async def chat_completion_tools_handler(
  133. request: Request, body: dict, user: UserModel, models, extra_params: dict
  134. ) -> tuple[dict, dict]:
  135. async def get_content_from_response(response) -> Optional[str]:
  136. content = None
  137. if hasattr(response, "body_iterator"):
  138. async for chunk in response.body_iterator:
  139. data = json.loads(chunk.decode("utf-8"))
  140. content = data["choices"][0]["message"]["content"]
  141. # Cleanup any remaining background tasks if necessary
  142. if response.background is not None:
  143. await response.background()
  144. else:
  145. content = response["choices"][0]["message"]["content"]
  146. return content
  147. def get_tools_function_calling_payload(messages, task_model_id, content):
  148. user_message = get_last_user_message(messages)
  149. history = "\n".join(
  150. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  151. for message in messages[::-1][:4]
  152. )
  153. prompt = f"History:\n{history}\nQuery: {user_message}"
  154. return {
  155. "model": task_model_id,
  156. "messages": [
  157. {"role": "system", "content": content},
  158. {"role": "user", "content": f"Query: {prompt}"},
  159. ],
  160. "stream": False,
  161. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  162. }
  163. # If tool_ids field is present, call the functions
  164. metadata = body.get("metadata", {})
  165. tool_ids = metadata.get("tool_ids", None)
  166. log.debug(f"{tool_ids=}")
  167. if not tool_ids:
  168. return body, {}
  169. skip_files = False
  170. sources = []
  171. task_model_id = get_task_model_id(
  172. body["model"],
  173. request.app.state.config.TASK_MODEL,
  174. request.app.state.config.TASK_MODEL_EXTERNAL,
  175. models,
  176. )
  177. tools = get_tools(
  178. request,
  179. tool_ids,
  180. user,
  181. {
  182. **extra_params,
  183. "__model__": models[task_model_id],
  184. "__messages__": body["messages"],
  185. "__files__": metadata.get("files", []),
  186. },
  187. )
  188. log.info(f"{tools=}")
  189. specs = [tool["spec"] for tool in tools.values()]
  190. tools_specs = json.dumps(specs)
  191. if request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  192. template = request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  193. else:
  194. template = DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  195. tools_function_calling_prompt = tools_function_calling_generation_template(
  196. template, tools_specs
  197. )
  198. log.info(f"{tools_function_calling_prompt=}")
  199. payload = get_tools_function_calling_payload(
  200. body["messages"], task_model_id, tools_function_calling_prompt
  201. )
  202. try:
  203. response = await generate_chat_completion(request, form_data=payload, user=user)
  204. log.debug(f"{response=}")
  205. content = await get_content_from_response(response)
  206. log.debug(f"{content=}")
  207. if not content:
  208. return body, {}
  209. try:
  210. content = content[content.find("{") : content.rfind("}") + 1]
  211. if not content:
  212. raise Exception("No JSON object found in the response")
  213. result = json.loads(content)
  214. tool_function_name = result.get("name", None)
  215. if tool_function_name not in tools:
  216. return body, {}
  217. tool_function_params = result.get("parameters", {})
  218. try:
  219. required_params = (
  220. tools[tool_function_name]
  221. .get("spec", {})
  222. .get("parameters", {})
  223. .get("required", [])
  224. )
  225. tool_function = tools[tool_function_name]["callable"]
  226. tool_function_params = {
  227. k: v
  228. for k, v in tool_function_params.items()
  229. if k in required_params
  230. }
  231. tool_output = await tool_function(**tool_function_params)
  232. except Exception as e:
  233. tool_output = str(e)
  234. if isinstance(tool_output, str):
  235. if tools[tool_function_name]["citation"]:
  236. sources.append(
  237. {
  238. "source": {
  239. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  240. },
  241. "document": [tool_output],
  242. "metadata": [
  243. {
  244. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  245. }
  246. ],
  247. }
  248. )
  249. else:
  250. sources.append(
  251. {
  252. "source": {},
  253. "document": [tool_output],
  254. "metadata": [
  255. {
  256. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  257. }
  258. ],
  259. }
  260. )
  261. if tools[tool_function_name]["file_handler"]:
  262. skip_files = True
  263. except Exception as e:
  264. log.exception(f"Error: {e}")
  265. content = None
  266. except Exception as e:
  267. log.exception(f"Error: {e}")
  268. content = None
  269. log.debug(f"tool_contexts: {sources}")
  270. if skip_files and "files" in body.get("metadata", {}):
  271. del body["metadata"]["files"]
  272. return body, {"sources": sources}
  273. async def chat_completion_files_handler(
  274. request: Request, body: dict, user: UserModel
  275. ) -> tuple[dict, dict[str, list]]:
  276. sources = []
  277. if files := body.get("metadata", {}).get("files", None):
  278. try:
  279. queries_response = await generate_queries(
  280. {
  281. "model": body["model"],
  282. "messages": body["messages"],
  283. "type": "retrieval",
  284. },
  285. user,
  286. )
  287. queries_response = queries_response["choices"][0]["message"]["content"]
  288. try:
  289. bracket_start = queries_response.find("{")
  290. bracket_end = queries_response.rfind("}") + 1
  291. if bracket_start == -1 or bracket_end == -1:
  292. raise Exception("No JSON object found in the response")
  293. queries_response = queries_response[bracket_start:bracket_end]
  294. queries_response = json.loads(queries_response)
  295. except Exception as e:
  296. queries_response = {"queries": [queries_response]}
  297. queries = queries_response.get("queries", [])
  298. except Exception as e:
  299. queries = []
  300. if len(queries) == 0:
  301. queries = [get_last_user_message(body["messages"])]
  302. sources = get_sources_from_files(
  303. files=files,
  304. queries=queries,
  305. embedding_function=request.app.state.EMBEDDING_FUNCTION,
  306. k=request.app.state.config.TOP_K,
  307. reranking_function=request.app.state.rf,
  308. r=request.app.state.config.RELEVANCE_THRESHOLD,
  309. hybrid_search=request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  310. )
  311. log.debug(f"rag_contexts:sources: {sources}")
  312. return body, {"sources": sources}
  313. def apply_params_to_form_data(form_data, model):
  314. params = form_data.pop("params", {})
  315. if model.get("ollama"):
  316. form_data["options"] = params
  317. if "format" in params:
  318. form_data["format"] = params["format"]
  319. if "keep_alive" in params:
  320. form_data["keep_alive"] = params["keep_alive"]
  321. else:
  322. if "seed" in params:
  323. form_data["seed"] = params["seed"]
  324. if "stop" in params:
  325. form_data["stop"] = params["stop"]
  326. if "temperature" in params:
  327. form_data["temperature"] = params["temperature"]
  328. if "top_p" in params:
  329. form_data["top_p"] = params["top_p"]
  330. if "frequency_penalty" in params:
  331. form_data["frequency_penalty"] = params["frequency_penalty"]
  332. return form_data
  333. async def process_chat_payload(request, form_data, metadata, user, model):
  334. form_data = apply_params_to_form_data(form_data, model)
  335. log.debug(f"form_data: {form_data}")
  336. event_emitter = get_event_emitter(metadata)
  337. event_call = get_event_call(metadata)
  338. extra_params = {
  339. "__event_emitter__": event_emitter,
  340. "__event_call__": event_call,
  341. "__user__": {
  342. "id": user.id,
  343. "email": user.email,
  344. "name": user.name,
  345. "role": user.role,
  346. },
  347. "__metadata__": metadata,
  348. "__request__": request,
  349. }
  350. # Initialize events to store additional event to be sent to the client
  351. # Initialize contexts and citation
  352. models = request.app.state.MODELS
  353. events = []
  354. sources = []
  355. user_message = get_last_user_message(form_data["messages"])
  356. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  357. if model_knowledge:
  358. await event_emitter(
  359. {
  360. "type": "status",
  361. "data": {
  362. "action": "knowledge_search",
  363. "query": user_message,
  364. "done": False,
  365. },
  366. }
  367. )
  368. knowledge_files = []
  369. for item in model_knowledge:
  370. print(item)
  371. if item.get("collection_name"):
  372. knowledge_files.append(
  373. {
  374. "id": item.get("collection_name"),
  375. "name": item.get("name"),
  376. "legacy": True,
  377. }
  378. )
  379. elif item.get("collection_names"):
  380. knowledge_files.append(
  381. {
  382. "name": item.get("name"),
  383. "type": "collection",
  384. "collection_names": item.get("collection_names"),
  385. "legacy": True,
  386. }
  387. )
  388. else:
  389. knowledge_files.append(item)
  390. files = form_data.get("files", [])
  391. files.extend(knowledge_files)
  392. form_data["files"] = files
  393. try:
  394. form_data, flags = await chat_completion_filter_functions_handler(
  395. request, form_data, model, extra_params
  396. )
  397. except Exception as e:
  398. return Exception(f"Error: {e}")
  399. tool_ids = form_data.pop("tool_ids", None)
  400. files = form_data.pop("files", None)
  401. # Remove files duplicates
  402. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  403. metadata = {
  404. **metadata,
  405. "tool_ids": tool_ids,
  406. "files": files,
  407. }
  408. form_data["metadata"] = metadata
  409. try:
  410. form_data, flags = await chat_completion_tools_handler(
  411. request, form_data, user, models, extra_params
  412. )
  413. sources.extend(flags.get("sources", []))
  414. except Exception as e:
  415. log.exception(e)
  416. try:
  417. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  418. sources.extend(flags.get("sources", []))
  419. except Exception as e:
  420. log.exception(e)
  421. # If context is not empty, insert it into the messages
  422. if len(sources) > 0:
  423. context_string = ""
  424. for source_idx, source in enumerate(sources):
  425. source_id = source.get("source", {}).get("name", "")
  426. if "document" in source:
  427. for doc_idx, doc_context in enumerate(source["document"]):
  428. metadata = source.get("metadata")
  429. doc_source_id = None
  430. if metadata:
  431. doc_source_id = metadata[doc_idx].get("source", source_id)
  432. if source_id:
  433. 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"
  434. else:
  435. # If there is no source_id, then do not include the source_id tag
  436. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  437. context_string = context_string.strip()
  438. prompt = get_last_user_message(form_data["messages"])
  439. if prompt is None:
  440. raise Exception("No user message found")
  441. if (
  442. request.app.state.config.RELEVANCE_THRESHOLD == 0
  443. and context_string.strip() == ""
  444. ):
  445. log.debug(
  446. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  447. )
  448. # Workaround for Ollama 2.0+ system prompt issue
  449. # TODO: replace with add_or_update_system_message
  450. if model["owned_by"] == "ollama":
  451. form_data["messages"] = prepend_to_first_user_message_content(
  452. rag_template(
  453. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  454. ),
  455. form_data["messages"],
  456. )
  457. else:
  458. form_data["messages"] = add_or_update_system_message(
  459. rag_template(
  460. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  461. ),
  462. form_data["messages"],
  463. )
  464. # If there are citations, add them to the data_items
  465. sources = [source for source in sources if source.get("source", {}).get("name", "")]
  466. if len(sources) > 0:
  467. events.append({"sources": sources})
  468. if model_knowledge:
  469. await event_emitter(
  470. {
  471. "type": "status",
  472. "data": {
  473. "action": "knowledge_search",
  474. "query": user_message,
  475. "done": True,
  476. "hidden": True,
  477. },
  478. }
  479. )
  480. return form_data, events
  481. async def process_chat_response(request, response, user, events, metadata, tasks):
  482. if not isinstance(response, StreamingResponse):
  483. return response
  484. if not any(
  485. content_type in response.headers["Content-Type"]
  486. for content_type in ["text/event-stream", "application/x-ndjson"]
  487. ):
  488. return response
  489. event_emitter = None
  490. if (
  491. "session_id" in metadata
  492. and metadata["session_id"]
  493. and "chat_id" in metadata
  494. and metadata["chat_id"]
  495. and "message_id" in metadata
  496. and metadata["message_id"]
  497. ):
  498. event_emitter = get_event_emitter(metadata)
  499. if event_emitter:
  500. task_id = str(uuid4()) # Create a unique task ID.
  501. # Handle as a background task
  502. async def post_response_handler(response, events):
  503. try:
  504. for event in events:
  505. await event_emitter(
  506. {
  507. "type": "chat:completion",
  508. "data": event,
  509. }
  510. )
  511. # Save message in the database
  512. Chats.upsert_message_to_chat_by_id_and_message_id(
  513. metadata["chat_id"],
  514. metadata["message_id"],
  515. {
  516. **event,
  517. },
  518. )
  519. content = ""
  520. async for line in response.body_iterator:
  521. line = line.decode("utf-8") if isinstance(line, bytes) else line
  522. data = line
  523. # Skip empty lines
  524. if not data.strip():
  525. continue
  526. # "data: " is the prefix for each event
  527. if not data.startswith("data: "):
  528. continue
  529. # Remove the prefix
  530. data = data[len("data: ") :]
  531. try:
  532. data = json.loads(data)
  533. value = (
  534. data.get("choices", [])[0].get("delta", {}).get("content")
  535. )
  536. if value:
  537. content = f"{content}{value}"
  538. # Save message in the database
  539. Chats.upsert_message_to_chat_by_id_and_message_id(
  540. metadata["chat_id"],
  541. metadata["message_id"],
  542. {
  543. "content": content,
  544. },
  545. )
  546. except Exception as e:
  547. done = "data: [DONE]" in line
  548. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  549. if done:
  550. data = {"done": True, "content": content, "title": title}
  551. # Send a webhook notification if the user is not active
  552. if (
  553. get_user_id_from_session_pool(metadata["session_id"])
  554. is None
  555. ):
  556. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  557. if webhook_url:
  558. post_webhook(
  559. webhook_url,
  560. f"{title} - {WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  561. {
  562. "action": "chat",
  563. "message": content,
  564. "title": title,
  565. "url": f"{WEBUI_URL}/c/{metadata['chat_id']}",
  566. },
  567. )
  568. else:
  569. continue
  570. await event_emitter(
  571. {
  572. "type": "chat:completion",
  573. "data": data,
  574. }
  575. )
  576. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  577. message = message_map.get(metadata["message_id"])
  578. if message:
  579. messages = get_message_list(message_map, message.get("id"))
  580. if tasks:
  581. if TASKS.TITLE_GENERATION in tasks:
  582. if tasks[TASKS.TITLE_GENERATION]:
  583. res = await generate_title(
  584. request,
  585. {
  586. "model": message["model"],
  587. "messages": messages,
  588. "chat_id": metadata["chat_id"],
  589. },
  590. user,
  591. )
  592. if res and isinstance(res, dict):
  593. title = (
  594. res.get("choices", [])[0]
  595. .get("message", {})
  596. .get(
  597. "content",
  598. message.get("content", "New Chat"),
  599. )
  600. )
  601. Chats.update_chat_title_by_id(
  602. metadata["chat_id"], title
  603. )
  604. await event_emitter(
  605. {
  606. "type": "chat:title",
  607. "data": title,
  608. }
  609. )
  610. elif len(messages) == 2:
  611. title = messages[0].get("content", "New Chat")
  612. Chats.update_chat_title_by_id(
  613. metadata["chat_id"], title
  614. )
  615. await event_emitter(
  616. {
  617. "type": "chat:title",
  618. "data": message.get("content", "New Chat"),
  619. }
  620. )
  621. if (
  622. TASKS.TAGS_GENERATION in tasks
  623. and tasks[TASKS.TAGS_GENERATION]
  624. ):
  625. res = await generate_chat_tags(
  626. request,
  627. {
  628. "model": message["model"],
  629. "messages": messages,
  630. "chat_id": metadata["chat_id"],
  631. },
  632. user,
  633. )
  634. if res and isinstance(res, dict):
  635. tags_string = (
  636. res.get("choices", [])[0]
  637. .get("message", {})
  638. .get("content", "")
  639. )
  640. tags_string = tags_string[
  641. tags_string.find("{") : tags_string.rfind("}") + 1
  642. ]
  643. try:
  644. tags = json.loads(tags_string).get("tags", [])
  645. Chats.update_chat_tags_by_id(
  646. metadata["chat_id"], tags, user
  647. )
  648. await event_emitter(
  649. {
  650. "type": "chat:tags",
  651. "data": tags,
  652. }
  653. )
  654. except Exception as e:
  655. print(f"Error: {e}")
  656. except asyncio.CancelledError:
  657. print("Task was cancelled!")
  658. await event_emitter({"type": "task-cancelled"})
  659. if response.background is not None:
  660. await response.background()
  661. # background_tasks.add_task(post_response_handler, response, events)
  662. task_id, _ = create_task(post_response_handler(response, events))
  663. return {"status": True, "task_id": task_id}
  664. else:
  665. # Fallback to the original response
  666. async def stream_wrapper(original_generator, events):
  667. def wrap_item(item):
  668. return f"data: {item}\n\n"
  669. for event in events:
  670. yield wrap_item(json.dumps(event))
  671. async for data in original_generator:
  672. yield data
  673. return StreamingResponse(
  674. stream_wrapper(response.body_iterator, events),
  675. headers=dict(response.headers),
  676. )