1
0

middleware.py 122 KB

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