middleware.py 123 KB

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