1
0

middleware.py 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051
  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. )
  76. from open_webui.utils.tools import get_tools
  77. from open_webui.utils.plugin import load_function_module_by_id
  78. from open_webui.utils.filter import (
  79. get_sorted_filter_ids,
  80. process_filter_functions,
  81. )
  82. from open_webui.utils.code_interpreter import execute_code_jupyter
  83. from open_webui.utils.payload import apply_system_prompt_to_body
  84. from open_webui.utils.mcp.client import MCPClient
  85. from open_webui.config import (
  86. CACHE_DIR,
  87. DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  88. DEFAULT_CODE_INTERPRETER_PROMPT,
  89. CODE_INTERPRETER_BLOCKED_MODULES,
  90. )
  91. from open_webui.env import (
  92. SRC_LOG_LEVELS,
  93. GLOBAL_LOG_LEVEL,
  94. CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
  95. CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES,
  96. BYPASS_MODEL_ACCESS_CONTROL,
  97. ENABLE_REALTIME_CHAT_SAVE,
  98. ENABLE_QUERIES_CACHE,
  99. )
  100. from open_webui.constants import TASKS
  101. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  102. log = logging.getLogger(__name__)
  103. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  104. DEFAULT_REASONING_TAGS = [
  105. ("<think>", "</think>"),
  106. ("<thinking>", "</thinking>"),
  107. ("<reason>", "</reason>"),
  108. ("<reasoning>", "</reasoning>"),
  109. ("<thought>", "</thought>"),
  110. ("<Thought>", "</Thought>"),
  111. ("<|begin_of_thought|>", "<|end_of_thought|>"),
  112. ("◁think▷", "◁/think▷"),
  113. ]
  114. DEFAULT_SOLUTION_TAGS = [("<|begin_of_solution|>", "<|end_of_solution|>")]
  115. DEFAULT_CODE_INTERPRETER_TAGS = [("<code_interpreter>", "</code_interpreter>")]
  116. def process_tool_result(
  117. request,
  118. tool_function_name,
  119. tool_result,
  120. tool_type,
  121. direct_tool=False,
  122. metadata=None,
  123. user=None,
  124. ):
  125. tool_result_embeds = []
  126. if isinstance(tool_result, HTMLResponse):
  127. content_disposition = tool_result.headers.get("Content-Disposition", "")
  128. if "inline" in content_disposition:
  129. content = tool_result.body.decode("utf-8")
  130. tool_result_embeds.append(content)
  131. if 200 <= tool_result.status_code < 300:
  132. tool_result = {
  133. "status": "success",
  134. "code": "ui_component",
  135. "message": f"{tool_function_name}: Embedded UI result is active and visible to the user.",
  136. }
  137. elif 400 <= tool_result.status_code < 500:
  138. tool_result = {
  139. "status": "error",
  140. "code": "ui_component",
  141. "message": f"{tool_function_name}: Client error {tool_result.status_code} from embedded UI result.",
  142. }
  143. elif 500 <= tool_result.status_code < 600:
  144. tool_result = {
  145. "status": "error",
  146. "code": "ui_component",
  147. "message": f"{tool_function_name}: Server error {tool_result.status_code} from embedded UI result.",
  148. }
  149. else:
  150. tool_result = {
  151. "status": "error",
  152. "code": "ui_component",
  153. "message": f"{tool_function_name}: Unexpected status code {tool_result.status_code} from embedded UI result.",
  154. }
  155. else:
  156. tool_result = tool_result.body.decode("utf-8")
  157. elif (tool_type == "external" and isinstance(tool_result, tuple)) or (
  158. direct_tool and isinstance(tool_result, list) and len(tool_result) == 2
  159. ):
  160. tool_result, tool_response_headers = tool_result
  161. try:
  162. if not isinstance(tool_response_headers, dict):
  163. tool_response_headers = dict(tool_response_headers)
  164. except Exception as e:
  165. tool_response_headers = {}
  166. log.debug(e)
  167. if tool_response_headers and isinstance(tool_response_headers, dict):
  168. content_disposition = tool_response_headers.get(
  169. "Content-Disposition",
  170. tool_response_headers.get("content-disposition", ""),
  171. )
  172. if "inline" in content_disposition:
  173. content_type = tool_response_headers.get(
  174. "Content-Type",
  175. tool_response_headers.get("content-type", ""),
  176. )
  177. location = tool_response_headers.get(
  178. "Location",
  179. tool_response_headers.get("location", ""),
  180. )
  181. if "text/html" in content_type:
  182. # Display as iframe embed
  183. tool_result_embeds.append(tool_result)
  184. tool_result = {
  185. "status": "success",
  186. "code": "ui_component",
  187. "message": f"{tool_function_name}: Embedded UI result is active and visible to the user.",
  188. }
  189. elif location:
  190. tool_result_embeds.append(location)
  191. tool_result = {
  192. "status": "success",
  193. "code": "ui_component",
  194. "message": f"{tool_function_name}: Embedded UI result is active and visible to the user.",
  195. }
  196. tool_result_files = []
  197. if isinstance(tool_result, list):
  198. if tool_type == "mcp": # MCP
  199. tool_response = []
  200. for item in tool_result:
  201. if isinstance(item, dict):
  202. if item.get("type") == "text":
  203. text = item.get("text", "")
  204. if isinstance(text, str):
  205. try:
  206. text = json.loads(text)
  207. except json.JSONDecodeError:
  208. pass
  209. tool_response.append(text)
  210. elif item.get("type") in ["image", "audio"]:
  211. file_url = get_file_url_from_base64(
  212. request,
  213. f"data:{item.get('mimeType')};base64,{item.get('data', item.get('blob', ''))}",
  214. {
  215. "chat_id": metadata.get("chat_id", None),
  216. "message_id": metadata.get("message_id", None),
  217. "session_id": metadata.get("session_id", None),
  218. "result": item,
  219. },
  220. user,
  221. )
  222. tool_result_files.append(
  223. {
  224. "type": item.get("type", "data"),
  225. "url": file_url,
  226. }
  227. )
  228. tool_result = tool_response[0] if len(tool_response) == 1 else tool_response
  229. else: # OpenAPI
  230. for item in tool_result:
  231. if isinstance(item, str) and item.startswith("data:"):
  232. tool_result_files.append(
  233. {
  234. "type": "data",
  235. "content": item,
  236. }
  237. )
  238. tool_result.remove(item)
  239. if isinstance(tool_result, list):
  240. tool_result = {"results": tool_result}
  241. if isinstance(tool_result, dict) or isinstance(tool_result, list):
  242. tool_result = json.dumps(tool_result, indent=2, ensure_ascii=False)
  243. return tool_result, tool_result_files, tool_result_embeds
  244. async def chat_completion_tools_handler(
  245. request: Request, body: dict, extra_params: dict, user: UserModel, models, tools
  246. ) -> tuple[dict, dict]:
  247. async def get_content_from_response(response) -> Optional[str]:
  248. content = None
  249. if hasattr(response, "body_iterator"):
  250. async for chunk in response.body_iterator:
  251. data = json.loads(chunk.decode("utf-8"))
  252. content = data["choices"][0]["message"]["content"]
  253. # Cleanup any remaining background tasks if necessary
  254. if response.background is not None:
  255. await response.background()
  256. else:
  257. content = response["choices"][0]["message"]["content"]
  258. return content
  259. def get_tools_function_calling_payload(messages, task_model_id, content):
  260. user_message = get_last_user_message(messages)
  261. recent_messages = messages[-4:] if len(messages) > 4 else messages
  262. chat_history = "\n".join(
  263. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  264. for message in recent_messages
  265. )
  266. prompt = f"History:\n{chat_history}\nQuery: {user_message}"
  267. return {
  268. "model": task_model_id,
  269. "messages": [
  270. {"role": "system", "content": content},
  271. {"role": "user", "content": f"Query: {prompt}"},
  272. ],
  273. "stream": False,
  274. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  275. }
  276. event_caller = extra_params["__event_call__"]
  277. event_emitter = extra_params["__event_emitter__"]
  278. metadata = extra_params["__metadata__"]
  279. task_model_id = get_task_model_id(
  280. body["model"],
  281. request.app.state.config.TASK_MODEL,
  282. request.app.state.config.TASK_MODEL_EXTERNAL,
  283. models,
  284. )
  285. skip_files = False
  286. sources = []
  287. specs = [tool["spec"] for tool in tools.values()]
  288. tools_specs = json.dumps(specs)
  289. if request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  290. template = request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  291. else:
  292. template = DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  293. tools_function_calling_prompt = tools_function_calling_generation_template(
  294. template, tools_specs
  295. )
  296. payload = get_tools_function_calling_payload(
  297. body["messages"], task_model_id, tools_function_calling_prompt
  298. )
  299. try:
  300. response = await generate_chat_completion(request, form_data=payload, user=user)
  301. log.debug(f"{response=}")
  302. content = await get_content_from_response(response)
  303. log.debug(f"{content=}")
  304. if not content:
  305. return body, {}
  306. try:
  307. content = content[content.find("{") : content.rfind("}") + 1]
  308. if not content:
  309. raise Exception("No JSON object found in the response")
  310. result = json.loads(content)
  311. async def tool_call_handler(tool_call):
  312. nonlocal skip_files
  313. log.debug(f"{tool_call=}")
  314. tool_function_name = tool_call.get("name", None)
  315. if tool_function_name not in tools:
  316. return body, {}
  317. tool_function_params = tool_call.get("parameters", {})
  318. tool = None
  319. tool_type = ""
  320. direct_tool = False
  321. try:
  322. tool = tools[tool_function_name]
  323. tool_type = tool.get("type", "")
  324. direct_tool = tool.get("direct", False)
  325. spec = tool.get("spec", {})
  326. allowed_params = (
  327. spec.get("parameters", {}).get("properties", {}).keys()
  328. )
  329. tool_function_params = {
  330. k: v
  331. for k, v in tool_function_params.items()
  332. if k in allowed_params
  333. }
  334. if tool.get("direct", False):
  335. tool_result = await event_caller(
  336. {
  337. "type": "execute:tool",
  338. "data": {
  339. "id": str(uuid4()),
  340. "name": tool_function_name,
  341. "params": tool_function_params,
  342. "server": tool.get("server", {}),
  343. "session_id": metadata.get("session_id", None),
  344. },
  345. }
  346. )
  347. else:
  348. tool_function = tool["callable"]
  349. tool_result = await tool_function(**tool_function_params)
  350. except Exception as e:
  351. tool_result = str(e)
  352. tool_result, tool_result_files, tool_result_embeds = (
  353. process_tool_result(
  354. request,
  355. tool_function_name,
  356. tool_result,
  357. tool_type,
  358. direct_tool,
  359. metadata,
  360. user,
  361. )
  362. )
  363. if event_emitter:
  364. if tool_result_files:
  365. await event_emitter(
  366. {
  367. "type": "files",
  368. "data": {
  369. "files": tool_result_files,
  370. },
  371. }
  372. )
  373. if tool_result_embeds:
  374. await event_emitter(
  375. {
  376. "type": "embeds",
  377. "data": {
  378. "embeds": tool_result_embeds,
  379. },
  380. }
  381. )
  382. print(
  383. f"Tool {tool_function_name} result: {tool_result}",
  384. tool_result_files,
  385. tool_result_embeds,
  386. )
  387. if tool_result:
  388. tool = tools[tool_function_name]
  389. tool_id = tool.get("tool_id", "")
  390. tool_name = (
  391. f"{tool_id}/{tool_function_name}"
  392. if tool_id
  393. else f"{tool_function_name}"
  394. )
  395. # Citation is enabled for this tool
  396. sources.append(
  397. {
  398. "source": {
  399. "name": (f"{tool_name}"),
  400. },
  401. "document": [str(tool_result)],
  402. "metadata": [
  403. {
  404. "source": (f"{tool_name}"),
  405. "parameters": tool_function_params,
  406. }
  407. ],
  408. "tool_result": True,
  409. }
  410. )
  411. # Citation is not enabled for this tool
  412. body["messages"] = add_or_update_user_message(
  413. f"\nTool `{tool_name}` Output: {tool_result}",
  414. body["messages"],
  415. )
  416. if (
  417. tools[tool_function_name]
  418. .get("metadata", {})
  419. .get("file_handler", False)
  420. ):
  421. skip_files = True
  422. # check if "tool_calls" in result
  423. if result.get("tool_calls"):
  424. for tool_call in result.get("tool_calls"):
  425. await tool_call_handler(tool_call)
  426. else:
  427. await tool_call_handler(result)
  428. except Exception as e:
  429. log.debug(f"Error: {e}")
  430. content = None
  431. except Exception as e:
  432. log.debug(f"Error: {e}")
  433. content = None
  434. log.debug(f"tool_contexts: {sources}")
  435. if skip_files and "files" in body.get("metadata", {}):
  436. del body["metadata"]["files"]
  437. return body, {"sources": sources}
  438. async def chat_memory_handler(
  439. request: Request, form_data: dict, extra_params: dict, user
  440. ):
  441. try:
  442. results = await query_memory(
  443. request,
  444. QueryMemoryForm(
  445. **{
  446. "content": get_last_user_message(form_data["messages"]) or "",
  447. "k": 3,
  448. }
  449. ),
  450. user,
  451. )
  452. except Exception as e:
  453. log.debug(e)
  454. results = None
  455. user_context = ""
  456. if results and hasattr(results, "documents"):
  457. if results.documents and len(results.documents) > 0:
  458. for doc_idx, doc in enumerate(results.documents[0]):
  459. created_at_date = "Unknown Date"
  460. if results.metadatas[0][doc_idx].get("created_at"):
  461. created_at_timestamp = results.metadatas[0][doc_idx]["created_at"]
  462. created_at_date = time.strftime(
  463. "%Y-%m-%d", time.localtime(created_at_timestamp)
  464. )
  465. user_context += f"{doc_idx + 1}. [{created_at_date}] {doc}\n"
  466. form_data["messages"] = add_or_update_system_message(
  467. f"User Context:\n{user_context}\n", form_data["messages"], append=True
  468. )
  469. return form_data
  470. async def chat_web_search_handler(
  471. request: Request, form_data: dict, extra_params: dict, user
  472. ):
  473. event_emitter = extra_params["__event_emitter__"]
  474. await event_emitter(
  475. {
  476. "type": "status",
  477. "data": {
  478. "action": "web_search",
  479. "description": "Searching the web",
  480. "done": False,
  481. },
  482. }
  483. )
  484. messages = form_data["messages"]
  485. user_message = get_last_user_message(messages)
  486. queries = []
  487. try:
  488. res = await generate_queries(
  489. request,
  490. {
  491. "model": form_data["model"],
  492. "messages": messages,
  493. "prompt": user_message,
  494. "type": "web_search",
  495. },
  496. user,
  497. )
  498. response = res["choices"][0]["message"]["content"]
  499. try:
  500. bracket_start = response.find("{")
  501. bracket_end = response.rfind("}") + 1
  502. if bracket_start == -1 or bracket_end == -1:
  503. raise Exception("No JSON object found in the response")
  504. response = response[bracket_start:bracket_end]
  505. queries = json.loads(response)
  506. queries = queries.get("queries", [])
  507. except Exception as e:
  508. queries = [response]
  509. if ENABLE_QUERIES_CACHE:
  510. request.state.cached_queries = queries
  511. except Exception as e:
  512. log.exception(e)
  513. queries = [user_message]
  514. # Check if generated queries are empty
  515. if len(queries) == 1 and queries[0].strip() == "":
  516. queries = [user_message]
  517. # Check if queries are not found
  518. if len(queries) == 0:
  519. await event_emitter(
  520. {
  521. "type": "status",
  522. "data": {
  523. "action": "web_search",
  524. "description": "No search query generated",
  525. "done": True,
  526. },
  527. }
  528. )
  529. return form_data
  530. await event_emitter(
  531. {
  532. "type": "status",
  533. "data": {
  534. "action": "web_search_queries_generated",
  535. "queries": queries,
  536. "done": False,
  537. },
  538. }
  539. )
  540. try:
  541. results = await process_web_search(
  542. request,
  543. SearchForm(queries=queries),
  544. user=user,
  545. )
  546. if results:
  547. files = form_data.get("files", [])
  548. if results.get("collection_names"):
  549. for col_idx, collection_name in enumerate(
  550. results.get("collection_names")
  551. ):
  552. files.append(
  553. {
  554. "collection_name": collection_name,
  555. "name": ", ".join(queries),
  556. "type": "web_search",
  557. "urls": results["filenames"],
  558. "queries": queries,
  559. }
  560. )
  561. elif results.get("docs"):
  562. # Invoked when bypass embedding and retrieval is set to True
  563. docs = results["docs"]
  564. files.append(
  565. {
  566. "docs": docs,
  567. "name": ", ".join(queries),
  568. "type": "web_search",
  569. "urls": results["filenames"],
  570. "queries": queries,
  571. }
  572. )
  573. form_data["files"] = files
  574. await event_emitter(
  575. {
  576. "type": "status",
  577. "data": {
  578. "action": "web_search",
  579. "description": "Searched {{count}} sites",
  580. "urls": results["filenames"],
  581. "items": results.get("items", []),
  582. "done": True,
  583. },
  584. }
  585. )
  586. else:
  587. await event_emitter(
  588. {
  589. "type": "status",
  590. "data": {
  591. "action": "web_search",
  592. "description": "No search results found",
  593. "done": True,
  594. "error": True,
  595. },
  596. }
  597. )
  598. except Exception as e:
  599. log.exception(e)
  600. await event_emitter(
  601. {
  602. "type": "status",
  603. "data": {
  604. "action": "web_search",
  605. "description": "An error occurred while searching the web",
  606. "queries": queries,
  607. "done": True,
  608. "error": True,
  609. },
  610. }
  611. )
  612. return form_data
  613. async def chat_image_generation_handler(
  614. request: Request, form_data: dict, extra_params: dict, user
  615. ):
  616. __event_emitter__ = extra_params["__event_emitter__"]
  617. await __event_emitter__(
  618. {
  619. "type": "status",
  620. "data": {"description": "Creating image", "done": False},
  621. }
  622. )
  623. messages = form_data["messages"]
  624. user_message = get_last_user_message(messages)
  625. prompt = user_message
  626. negative_prompt = ""
  627. if request.app.state.config.ENABLE_IMAGE_PROMPT_GENERATION:
  628. try:
  629. res = await generate_image_prompt(
  630. request,
  631. {
  632. "model": form_data["model"],
  633. "messages": messages,
  634. },
  635. user,
  636. )
  637. response = res["choices"][0]["message"]["content"]
  638. try:
  639. bracket_start = response.find("{")
  640. bracket_end = response.rfind("}") + 1
  641. if bracket_start == -1 or bracket_end == -1:
  642. raise Exception("No JSON object found in the response")
  643. response = response[bracket_start:bracket_end]
  644. response = json.loads(response)
  645. prompt = response.get("prompt", [])
  646. except Exception as e:
  647. prompt = user_message
  648. except Exception as e:
  649. log.exception(e)
  650. prompt = user_message
  651. system_message_content = ""
  652. try:
  653. images = await image_generations(
  654. request=request,
  655. form_data=GenerateImageForm(**{"prompt": prompt}),
  656. user=user,
  657. )
  658. await __event_emitter__(
  659. {
  660. "type": "status",
  661. "data": {"description": "Image created", "done": True},
  662. }
  663. )
  664. await __event_emitter__(
  665. {
  666. "type": "files",
  667. "data": {
  668. "files": [
  669. {
  670. "type": "image",
  671. "url": image["url"],
  672. }
  673. for image in images
  674. ]
  675. },
  676. }
  677. )
  678. system_message_content = "<context>User is shown the generated image, tell the user that the image has been generated</context>"
  679. except Exception as e:
  680. log.exception(e)
  681. await __event_emitter__(
  682. {
  683. "type": "status",
  684. "data": {
  685. "description": f"An error occurred while generating an image",
  686. "done": True,
  687. },
  688. }
  689. )
  690. system_message_content = "<context>Unable to generate an image, tell the user that an error occurred</context>"
  691. if system_message_content:
  692. form_data["messages"] = add_or_update_system_message(
  693. system_message_content, form_data["messages"]
  694. )
  695. return form_data
  696. async def chat_completion_files_handler(
  697. request: Request, body: dict, extra_params: dict, user: UserModel
  698. ) -> tuple[dict, dict[str, list]]:
  699. __event_emitter__ = extra_params["__event_emitter__"]
  700. sources = []
  701. if files := body.get("metadata", {}).get("files", None):
  702. # Check if all files are in full context mode
  703. all_full_context = all(item.get("context") == "full" for item in files)
  704. queries = []
  705. if not all_full_context:
  706. try:
  707. queries_response = await generate_queries(
  708. request,
  709. {
  710. "model": body["model"],
  711. "messages": body["messages"],
  712. "type": "retrieval",
  713. },
  714. user,
  715. )
  716. queries_response = queries_response["choices"][0]["message"]["content"]
  717. try:
  718. bracket_start = queries_response.find("{")
  719. bracket_end = queries_response.rfind("}") + 1
  720. if bracket_start == -1 or bracket_end == -1:
  721. raise Exception("No JSON object found in the response")
  722. queries_response = queries_response[bracket_start:bracket_end]
  723. queries_response = json.loads(queries_response)
  724. except Exception as e:
  725. queries_response = {"queries": [queries_response]}
  726. queries = queries_response.get("queries", [])
  727. except:
  728. pass
  729. if len(queries) == 0:
  730. queries = [get_last_user_message(body["messages"])]
  731. if not all_full_context:
  732. await __event_emitter__(
  733. {
  734. "type": "status",
  735. "data": {
  736. "action": "queries_generated",
  737. "queries": queries,
  738. "done": False,
  739. },
  740. }
  741. )
  742. try:
  743. # Offload get_sources_from_items to a separate thread
  744. loop = asyncio.get_running_loop()
  745. with ThreadPoolExecutor() as executor:
  746. sources = await loop.run_in_executor(
  747. executor,
  748. lambda: get_sources_from_items(
  749. request=request,
  750. items=files,
  751. queries=queries,
  752. embedding_function=lambda query, prefix: request.app.state.EMBEDDING_FUNCTION(
  753. query, prefix=prefix, user=user
  754. ),
  755. k=request.app.state.config.TOP_K,
  756. reranking_function=(
  757. (
  758. lambda sentences: request.app.state.RERANKING_FUNCTION(
  759. sentences, user=user
  760. )
  761. )
  762. if request.app.state.RERANKING_FUNCTION
  763. else None
  764. ),
  765. k_reranker=request.app.state.config.TOP_K_RERANKER,
  766. r=request.app.state.config.RELEVANCE_THRESHOLD,
  767. hybrid_bm25_weight=request.app.state.config.HYBRID_BM25_WEIGHT,
  768. hybrid_search=request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  769. full_context=all_full_context
  770. or request.app.state.config.RAG_FULL_CONTEXT,
  771. user=user,
  772. ),
  773. )
  774. except Exception as e:
  775. log.exception(e)
  776. log.debug(f"rag_contexts:sources: {sources}")
  777. unique_ids = set()
  778. for source in sources or []:
  779. if not source or len(source.keys()) == 0:
  780. continue
  781. documents = source.get("document") or []
  782. metadatas = source.get("metadata") or []
  783. src_info = source.get("source") or {}
  784. for index, _ in enumerate(documents):
  785. metadata = metadatas[index] if index < len(metadatas) else None
  786. _id = (
  787. (metadata or {}).get("source")
  788. or (src_info or {}).get("id")
  789. or "N/A"
  790. )
  791. unique_ids.add(_id)
  792. sources_count = len(unique_ids)
  793. await __event_emitter__(
  794. {
  795. "type": "status",
  796. "data": {
  797. "action": "sources_retrieved",
  798. "count": sources_count,
  799. "done": True,
  800. },
  801. }
  802. )
  803. return body, {"sources": sources}
  804. def apply_params_to_form_data(form_data, model):
  805. params = form_data.pop("params", {})
  806. custom_params = params.pop("custom_params", {})
  807. open_webui_params = {
  808. "stream_response": bool,
  809. "stream_delta_chunk_size": int,
  810. "function_calling": str,
  811. "reasoning_tags": list,
  812. "system": str,
  813. }
  814. for key in list(params.keys()):
  815. if key in open_webui_params:
  816. del params[key]
  817. if custom_params:
  818. # Attempt to parse custom_params if they are strings
  819. for key, value in custom_params.items():
  820. if isinstance(value, str):
  821. try:
  822. # Attempt to parse the string as JSON
  823. custom_params[key] = json.loads(value)
  824. except json.JSONDecodeError:
  825. # If it fails, keep the original string
  826. pass
  827. # If custom_params are provided, merge them into params
  828. params = deep_update(params, custom_params)
  829. if model.get("owned_by") == "ollama":
  830. # Ollama specific parameters
  831. form_data["options"] = params
  832. else:
  833. if isinstance(params, dict):
  834. for key, value in params.items():
  835. if value is not None:
  836. form_data[key] = value
  837. if "logit_bias" in params and params["logit_bias"] is not None:
  838. try:
  839. form_data["logit_bias"] = json.loads(
  840. convert_logit_bias_input_to_json(params["logit_bias"])
  841. )
  842. except Exception as e:
  843. log.exception(f"Error parsing logit_bias: {e}")
  844. return form_data
  845. async def process_chat_payload(request, form_data, user, metadata, model):
  846. # Pipeline Inlet -> Filter Inlet -> Chat Memory -> Chat Web Search -> Chat Image Generation
  847. # -> Chat Code Interpreter (Form Data Update) -> (Default) Chat Tools Function Calling
  848. # -> Chat Files
  849. form_data = apply_params_to_form_data(form_data, model)
  850. log.debug(f"form_data: {form_data}")
  851. system_message = get_system_message(form_data.get("messages", []))
  852. if system_message:
  853. try:
  854. form_data = apply_system_prompt_to_body(
  855. system_message.get("content"), form_data, metadata, user
  856. )
  857. except:
  858. pass
  859. event_emitter = get_event_emitter(metadata)
  860. event_call = get_event_call(metadata)
  861. oauth_token = None
  862. try:
  863. if request.cookies.get("oauth_session_id", None):
  864. oauth_token = await request.app.state.oauth_manager.get_oauth_token(
  865. user.id,
  866. request.cookies.get("oauth_session_id", None),
  867. )
  868. except Exception as e:
  869. log.error(f"Error getting OAuth token: {e}")
  870. extra_params = {
  871. "__event_emitter__": event_emitter,
  872. "__event_call__": event_call,
  873. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  874. "__metadata__": metadata,
  875. "__request__": request,
  876. "__model__": model,
  877. "__oauth_token__": oauth_token,
  878. }
  879. # Initialize events to store additional event to be sent to the client
  880. # Initialize contexts and citation
  881. if getattr(request.state, "direct", False) and hasattr(request.state, "model"):
  882. models = {
  883. request.state.model["id"]: request.state.model,
  884. }
  885. else:
  886. models = request.app.state.MODELS
  887. task_model_id = get_task_model_id(
  888. form_data["model"],
  889. request.app.state.config.TASK_MODEL,
  890. request.app.state.config.TASK_MODEL_EXTERNAL,
  891. models,
  892. )
  893. events = []
  894. sources = []
  895. # Folder "Project" handling
  896. # Check if the request has chat_id and is inside of a folder
  897. chat_id = metadata.get("chat_id", None)
  898. if chat_id and user:
  899. chat = Chats.get_chat_by_id_and_user_id(chat_id, user.id)
  900. if chat and chat.folder_id:
  901. folder = Folders.get_folder_by_id_and_user_id(chat.folder_id, user.id)
  902. if folder and folder.data:
  903. if "system_prompt" in folder.data:
  904. form_data = apply_system_prompt_to_body(
  905. folder.data["system_prompt"], form_data, metadata, user
  906. )
  907. if "files" in folder.data:
  908. form_data["files"] = [
  909. *folder.data["files"],
  910. *form_data.get("files", []),
  911. ]
  912. # Model "Knowledge" handling
  913. user_message = get_last_user_message(form_data["messages"])
  914. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  915. if model_knowledge:
  916. await event_emitter(
  917. {
  918. "type": "status",
  919. "data": {
  920. "action": "knowledge_search",
  921. "query": user_message,
  922. "done": False,
  923. },
  924. }
  925. )
  926. knowledge_files = []
  927. for item in model_knowledge:
  928. if item.get("collection_name"):
  929. knowledge_files.append(
  930. {
  931. "id": item.get("collection_name"),
  932. "name": item.get("name"),
  933. "legacy": True,
  934. }
  935. )
  936. elif item.get("collection_names"):
  937. knowledge_files.append(
  938. {
  939. "name": item.get("name"),
  940. "type": "collection",
  941. "collection_names": item.get("collection_names"),
  942. "legacy": True,
  943. }
  944. )
  945. else:
  946. knowledge_files.append(item)
  947. files = form_data.get("files", [])
  948. files.extend(knowledge_files)
  949. form_data["files"] = files
  950. variables = form_data.pop("variables", None)
  951. # Process the form_data through the pipeline
  952. try:
  953. form_data = await process_pipeline_inlet_filter(
  954. request, form_data, user, models
  955. )
  956. except Exception as e:
  957. raise e
  958. try:
  959. filter_functions = [
  960. Functions.get_function_by_id(filter_id)
  961. for filter_id in get_sorted_filter_ids(
  962. request, model, metadata.get("filter_ids", [])
  963. )
  964. ]
  965. form_data, flags = await process_filter_functions(
  966. request=request,
  967. filter_functions=filter_functions,
  968. filter_type="inlet",
  969. form_data=form_data,
  970. extra_params=extra_params,
  971. )
  972. except Exception as e:
  973. raise Exception(f"{e}")
  974. features = form_data.pop("features", None)
  975. if features:
  976. if "memory" in features and features["memory"]:
  977. form_data = await chat_memory_handler(
  978. request, form_data, extra_params, user
  979. )
  980. if "web_search" in features and features["web_search"]:
  981. form_data = await chat_web_search_handler(
  982. request, form_data, extra_params, user
  983. )
  984. if "image_generation" in features and features["image_generation"]:
  985. form_data = await chat_image_generation_handler(
  986. request, form_data, extra_params, user
  987. )
  988. if "code_interpreter" in features and features["code_interpreter"]:
  989. form_data["messages"] = add_or_update_user_message(
  990. (
  991. request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE
  992. if request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE != ""
  993. else DEFAULT_CODE_INTERPRETER_PROMPT
  994. ),
  995. form_data["messages"],
  996. )
  997. tool_ids = form_data.pop("tool_ids", None)
  998. files = form_data.pop("files", None)
  999. # Remove files duplicates
  1000. if files:
  1001. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  1002. metadata = {
  1003. **metadata,
  1004. "tool_ids": tool_ids,
  1005. "files": files,
  1006. }
  1007. form_data["metadata"] = metadata
  1008. # Server side tools
  1009. tool_ids = metadata.get("tool_ids", None)
  1010. # Client side tools
  1011. direct_tool_servers = metadata.get("tool_servers", None)
  1012. log.debug(f"{tool_ids=}")
  1013. log.debug(f"{direct_tool_servers=}")
  1014. tools_dict = {}
  1015. mcp_clients = {}
  1016. mcp_tools_dict = {}
  1017. if tool_ids:
  1018. for tool_id in tool_ids:
  1019. if tool_id.startswith("server:mcp:"):
  1020. try:
  1021. server_id = tool_id[len("server:mcp:") :]
  1022. mcp_server_connection = None
  1023. for (
  1024. server_connection
  1025. ) in request.app.state.config.TOOL_SERVER_CONNECTIONS:
  1026. if (
  1027. server_connection.get("type", "") == "mcp"
  1028. and server_connection.get("info", {}).get("id") == server_id
  1029. ):
  1030. mcp_server_connection = server_connection
  1031. break
  1032. if not mcp_server_connection:
  1033. log.error(f"MCP server with id {server_id} not found")
  1034. continue
  1035. auth_type = mcp_server_connection.get("auth_type", "")
  1036. headers = {}
  1037. if auth_type == "bearer":
  1038. headers["Authorization"] = (
  1039. f"Bearer {mcp_server_connection.get('key', '')}"
  1040. )
  1041. elif auth_type == "none":
  1042. # No authentication
  1043. pass
  1044. elif auth_type == "session":
  1045. headers["Authorization"] = (
  1046. f"Bearer {request.state.token.credentials}"
  1047. )
  1048. elif auth_type == "system_oauth":
  1049. oauth_token = extra_params.get("__oauth_token__", None)
  1050. if oauth_token:
  1051. headers["Authorization"] = (
  1052. f"Bearer {oauth_token.get('access_token', '')}"
  1053. )
  1054. elif auth_type == "oauth_2.1":
  1055. try:
  1056. splits = server_id.split(":")
  1057. server_id = splits[-1] if len(splits) > 1 else server_id
  1058. oauth_token = await request.app.state.oauth_client_manager.get_oauth_token(
  1059. user.id, f"mcp:{server_id}"
  1060. )
  1061. if oauth_token:
  1062. headers["Authorization"] = (
  1063. f"Bearer {oauth_token.get('access_token', '')}"
  1064. )
  1065. except Exception as e:
  1066. log.error(f"Error getting OAuth token: {e}")
  1067. oauth_token = None
  1068. mcp_clients[server_id] = MCPClient()
  1069. await mcp_clients[server_id].connect(
  1070. url=mcp_server_connection.get("url", ""),
  1071. headers=headers if headers else None,
  1072. )
  1073. tool_specs = await mcp_clients[server_id].list_tool_specs()
  1074. for tool_spec in tool_specs:
  1075. def make_tool_function(client, function_name):
  1076. async def tool_function(**kwargs):
  1077. print(kwargs)
  1078. print(client)
  1079. print(await client.list_tool_specs())
  1080. return await client.call_tool(
  1081. function_name,
  1082. function_args=kwargs,
  1083. )
  1084. return tool_function
  1085. tool_function = make_tool_function(
  1086. mcp_clients[server_id], tool_spec["name"]
  1087. )
  1088. mcp_tools_dict[f"{server_id}_{tool_spec['name']}"] = {
  1089. "spec": {
  1090. **tool_spec,
  1091. "name": f"{server_id}_{tool_spec['name']}",
  1092. },
  1093. "callable": tool_function,
  1094. "type": "mcp",
  1095. "client": mcp_clients[server_id],
  1096. "direct": False,
  1097. }
  1098. except Exception as e:
  1099. log.debug(e)
  1100. continue
  1101. tools_dict = await get_tools(
  1102. request,
  1103. tool_ids,
  1104. user,
  1105. {
  1106. **extra_params,
  1107. "__model__": models[task_model_id],
  1108. "__messages__": form_data["messages"],
  1109. "__files__": metadata.get("files", []),
  1110. },
  1111. )
  1112. if mcp_tools_dict:
  1113. tools_dict = {**tools_dict, **mcp_tools_dict}
  1114. if direct_tool_servers:
  1115. for tool_server in direct_tool_servers:
  1116. tool_specs = tool_server.pop("specs", [])
  1117. for tool in tool_specs:
  1118. tools_dict[tool["name"]] = {
  1119. "spec": tool,
  1120. "direct": True,
  1121. "server": tool_server,
  1122. }
  1123. if mcp_clients:
  1124. metadata["mcp_clients"] = mcp_clients
  1125. if tools_dict:
  1126. if metadata.get("params", {}).get("function_calling") == "native":
  1127. # If the function calling is native, then call the tools function calling handler
  1128. metadata["tools"] = tools_dict
  1129. form_data["tools"] = [
  1130. {"type": "function", "function": tool.get("spec", {})}
  1131. for tool in tools_dict.values()
  1132. ]
  1133. else:
  1134. # If the function calling is not native, then call the tools function calling handler
  1135. try:
  1136. form_data, flags = await chat_completion_tools_handler(
  1137. request, form_data, extra_params, user, models, tools_dict
  1138. )
  1139. sources.extend(flags.get("sources", []))
  1140. except Exception as e:
  1141. log.exception(e)
  1142. try:
  1143. form_data, flags = await chat_completion_files_handler(
  1144. request, form_data, extra_params, user
  1145. )
  1146. sources.extend(flags.get("sources", []))
  1147. except Exception as e:
  1148. log.exception(e)
  1149. # If context is not empty, insert it into the messages
  1150. if len(sources) > 0:
  1151. context_string = ""
  1152. citation_idx_map = {}
  1153. for source in sources:
  1154. if "document" in source:
  1155. for document_text, document_metadata in zip(
  1156. source["document"], source["metadata"]
  1157. ):
  1158. source_name = source.get("source", {}).get("name", None)
  1159. source_id = (
  1160. document_metadata.get("source", None)
  1161. or source.get("source", {}).get("id", None)
  1162. or "N/A"
  1163. )
  1164. if source_id not in citation_idx_map:
  1165. citation_idx_map[source_id] = len(citation_idx_map) + 1
  1166. context_string += (
  1167. f'<source id="{citation_idx_map[source_id]}"'
  1168. + (f' name="{source_name}"' if source_name else "")
  1169. + f">{document_text}</source>\n"
  1170. )
  1171. context_string = context_string.strip()
  1172. prompt = get_last_user_message(form_data["messages"])
  1173. if prompt is None:
  1174. raise Exception("No user message found")
  1175. if context_string != "":
  1176. form_data["messages"] = add_or_update_user_message(
  1177. rag_template(
  1178. request.app.state.config.RAG_TEMPLATE,
  1179. context_string,
  1180. prompt,
  1181. ),
  1182. form_data["messages"],
  1183. append=False,
  1184. )
  1185. # If there are citations, add them to the data_items
  1186. sources = [
  1187. source
  1188. for source in sources
  1189. if source.get("source", {}).get("name", "")
  1190. or source.get("source", {}).get("id", "")
  1191. ]
  1192. if len(sources) > 0:
  1193. events.append({"sources": sources})
  1194. if model_knowledge:
  1195. await event_emitter(
  1196. {
  1197. "type": "status",
  1198. "data": {
  1199. "action": "knowledge_search",
  1200. "query": user_message,
  1201. "done": True,
  1202. "hidden": True,
  1203. },
  1204. }
  1205. )
  1206. print("Final form_data:", form_data)
  1207. print("Final metadata:", metadata)
  1208. print("Final events:", events)
  1209. return form_data, metadata, events
  1210. async def process_chat_response(
  1211. request, response, form_data, user, metadata, model, events, tasks
  1212. ):
  1213. async def background_tasks_handler():
  1214. messages_map = Chats.get_messages_map_by_chat_id(metadata["chat_id"])
  1215. message = messages_map.get(metadata["message_id"]) if messages_map else None
  1216. if message:
  1217. message_list = get_message_list(messages_map, metadata["message_id"])
  1218. # Remove details tags and files from the messages.
  1219. # as get_message_list creates a new list, it does not affect
  1220. # the original messages outside of this handler
  1221. messages = []
  1222. for message in message_list:
  1223. content = message.get("content", "")
  1224. if isinstance(content, list):
  1225. for item in content:
  1226. if item.get("type") == "text":
  1227. content = item["text"]
  1228. break
  1229. if isinstance(content, str):
  1230. content = re.sub(
  1231. r"<details\b[^>]*>.*?<\/details>|!\[.*?\]\(.*?\)",
  1232. "",
  1233. content,
  1234. flags=re.S | re.I,
  1235. ).strip()
  1236. messages.append(
  1237. {
  1238. **message,
  1239. "role": message.get(
  1240. "role", "assistant"
  1241. ), # Safe fallback for missing role
  1242. "content": content,
  1243. }
  1244. )
  1245. if tasks and messages:
  1246. if (
  1247. TASKS.FOLLOW_UP_GENERATION in tasks
  1248. and tasks[TASKS.FOLLOW_UP_GENERATION]
  1249. ):
  1250. res = await generate_follow_ups(
  1251. request,
  1252. {
  1253. "model": message["model"],
  1254. "messages": messages,
  1255. "message_id": metadata["message_id"],
  1256. "chat_id": metadata["chat_id"],
  1257. },
  1258. user,
  1259. )
  1260. if res and isinstance(res, dict):
  1261. if len(res.get("choices", [])) == 1:
  1262. follow_ups_string = (
  1263. res.get("choices", [])[0]
  1264. .get("message", {})
  1265. .get("content", "")
  1266. )
  1267. else:
  1268. follow_ups_string = ""
  1269. follow_ups_string = follow_ups_string[
  1270. follow_ups_string.find("{") : follow_ups_string.rfind("}")
  1271. + 1
  1272. ]
  1273. try:
  1274. follow_ups = json.loads(follow_ups_string).get(
  1275. "follow_ups", []
  1276. )
  1277. Chats.upsert_message_to_chat_by_id_and_message_id(
  1278. metadata["chat_id"],
  1279. metadata["message_id"],
  1280. {
  1281. "followUps": follow_ups,
  1282. },
  1283. )
  1284. await event_emitter(
  1285. {
  1286. "type": "chat:message:follow_ups",
  1287. "data": {
  1288. "follow_ups": follow_ups,
  1289. },
  1290. }
  1291. )
  1292. except Exception as e:
  1293. pass
  1294. if TASKS.TITLE_GENERATION in tasks:
  1295. user_message = get_last_user_message(messages)
  1296. if user_message and len(user_message) > 100:
  1297. user_message = user_message[:100] + "..."
  1298. if tasks[TASKS.TITLE_GENERATION]:
  1299. res = await generate_title(
  1300. request,
  1301. {
  1302. "model": message["model"],
  1303. "messages": messages,
  1304. "chat_id": metadata["chat_id"],
  1305. },
  1306. user,
  1307. )
  1308. if res and isinstance(res, dict):
  1309. if len(res.get("choices", [])) == 1:
  1310. title_string = (
  1311. res.get("choices", [])[0]
  1312. .get("message", {})
  1313. .get(
  1314. "content", message.get("content", user_message)
  1315. )
  1316. )
  1317. else:
  1318. title_string = ""
  1319. title_string = title_string[
  1320. title_string.find("{") : title_string.rfind("}") + 1
  1321. ]
  1322. try:
  1323. title = json.loads(title_string).get(
  1324. "title", user_message
  1325. )
  1326. except Exception as e:
  1327. title = ""
  1328. if not title:
  1329. title = messages[0].get("content", user_message)
  1330. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1331. await event_emitter(
  1332. {
  1333. "type": "chat:title",
  1334. "data": title,
  1335. }
  1336. )
  1337. elif len(messages) == 2:
  1338. title = messages[0].get("content", user_message)
  1339. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1340. await event_emitter(
  1341. {
  1342. "type": "chat:title",
  1343. "data": message.get("content", user_message),
  1344. }
  1345. )
  1346. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  1347. res = await generate_chat_tags(
  1348. request,
  1349. {
  1350. "model": message["model"],
  1351. "messages": messages,
  1352. "chat_id": metadata["chat_id"],
  1353. },
  1354. user,
  1355. )
  1356. if res and isinstance(res, dict):
  1357. if len(res.get("choices", [])) == 1:
  1358. tags_string = (
  1359. res.get("choices", [])[0]
  1360. .get("message", {})
  1361. .get("content", "")
  1362. )
  1363. else:
  1364. tags_string = ""
  1365. tags_string = tags_string[
  1366. tags_string.find("{") : tags_string.rfind("}") + 1
  1367. ]
  1368. try:
  1369. tags = json.loads(tags_string).get("tags", [])
  1370. Chats.update_chat_tags_by_id(
  1371. metadata["chat_id"], tags, user
  1372. )
  1373. await event_emitter(
  1374. {
  1375. "type": "chat:tags",
  1376. "data": tags,
  1377. }
  1378. )
  1379. except Exception as e:
  1380. pass
  1381. event_emitter = None
  1382. event_caller = None
  1383. if (
  1384. "session_id" in metadata
  1385. and metadata["session_id"]
  1386. and "chat_id" in metadata
  1387. and metadata["chat_id"]
  1388. and "message_id" in metadata
  1389. and metadata["message_id"]
  1390. ):
  1391. event_emitter = get_event_emitter(metadata)
  1392. event_caller = get_event_call(metadata)
  1393. # Non-streaming response
  1394. if not isinstance(response, StreamingResponse):
  1395. if event_emitter:
  1396. try:
  1397. if isinstance(response, dict) or isinstance(response, JSONResponse):
  1398. if isinstance(response, list) and len(response) == 1:
  1399. # If the response is a single-item list, unwrap it #17213
  1400. response = response[0]
  1401. if isinstance(response, JSONResponse) and isinstance(
  1402. response.body, bytes
  1403. ):
  1404. try:
  1405. response_data = json.loads(response.body.decode("utf-8"))
  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 = line.decode("utf-8") if isinstance(line, bytes) else line
  1943. data = line
  1944. # Skip empty lines
  1945. if not data.strip():
  1946. continue
  1947. # "data:" is the prefix for each event
  1948. if not data.startswith("data:"):
  1949. continue
  1950. # Remove the prefix
  1951. data = data[len("data:") :].strip()
  1952. try:
  1953. data = json.loads(data)
  1954. data, _ = await process_filter_functions(
  1955. request=request,
  1956. filter_functions=filter_functions,
  1957. filter_type="stream",
  1958. form_data=data,
  1959. extra_params={"__body__": form_data, **extra_params},
  1960. )
  1961. if data:
  1962. if "event" in data:
  1963. await event_emitter(data.get("event", {}))
  1964. if "selected_model_id" in data:
  1965. model_id = data["selected_model_id"]
  1966. Chats.upsert_message_to_chat_by_id_and_message_id(
  1967. metadata["chat_id"],
  1968. metadata["message_id"],
  1969. {
  1970. "selectedModelId": model_id,
  1971. },
  1972. )
  1973. await event_emitter(
  1974. {
  1975. "type": "chat:completion",
  1976. "data": data,
  1977. }
  1978. )
  1979. else:
  1980. choices = data.get("choices", [])
  1981. # 17421
  1982. usage = data.get("usage", {}) or {}
  1983. usage.update(data.get("timings", {})) # llama.cpp
  1984. if usage:
  1985. await event_emitter(
  1986. {
  1987. "type": "chat:completion",
  1988. "data": {
  1989. "usage": usage,
  1990. },
  1991. }
  1992. )
  1993. if not choices:
  1994. error = data.get("error", {})
  1995. if error:
  1996. await event_emitter(
  1997. {
  1998. "type": "chat:completion",
  1999. "data": {
  2000. "error": error,
  2001. },
  2002. }
  2003. )
  2004. continue
  2005. delta = choices[0].get("delta", {})
  2006. delta_tool_calls = delta.get("tool_calls", None)
  2007. if delta_tool_calls:
  2008. for delta_tool_call in delta_tool_calls:
  2009. tool_call_index = delta_tool_call.get(
  2010. "index"
  2011. )
  2012. if tool_call_index is not None:
  2013. # Check if the tool call already exists
  2014. current_response_tool_call = None
  2015. for (
  2016. response_tool_call
  2017. ) in response_tool_calls:
  2018. if (
  2019. response_tool_call.get("index")
  2020. == tool_call_index
  2021. ):
  2022. current_response_tool_call = (
  2023. response_tool_call
  2024. )
  2025. break
  2026. if current_response_tool_call is None:
  2027. # Add the new tool call
  2028. delta_tool_call.setdefault(
  2029. "function", {}
  2030. )
  2031. delta_tool_call[
  2032. "function"
  2033. ].setdefault("name", "")
  2034. delta_tool_call[
  2035. "function"
  2036. ].setdefault("arguments", "")
  2037. response_tool_calls.append(
  2038. delta_tool_call
  2039. )
  2040. else:
  2041. # Update the existing tool call
  2042. delta_name = delta_tool_call.get(
  2043. "function", {}
  2044. ).get("name")
  2045. delta_arguments = (
  2046. delta_tool_call.get(
  2047. "function", {}
  2048. ).get("arguments")
  2049. )
  2050. if delta_name:
  2051. current_response_tool_call[
  2052. "function"
  2053. ]["name"] += delta_name
  2054. if delta_arguments:
  2055. current_response_tool_call[
  2056. "function"
  2057. ][
  2058. "arguments"
  2059. ] += delta_arguments
  2060. value = delta.get("content")
  2061. reasoning_content = (
  2062. delta.get("reasoning_content")
  2063. or delta.get("reasoning")
  2064. or delta.get("thinking")
  2065. )
  2066. if reasoning_content:
  2067. if (
  2068. not content_blocks
  2069. or content_blocks[-1]["type"] != "reasoning"
  2070. ):
  2071. reasoning_block = {
  2072. "type": "reasoning",
  2073. "start_tag": "<think>",
  2074. "end_tag": "</think>",
  2075. "attributes": {
  2076. "type": "reasoning_content"
  2077. },
  2078. "content": "",
  2079. "started_at": time.time(),
  2080. }
  2081. content_blocks.append(reasoning_block)
  2082. else:
  2083. reasoning_block = content_blocks[-1]
  2084. reasoning_block["content"] += reasoning_content
  2085. data = {
  2086. "content": serialize_content_blocks(
  2087. content_blocks
  2088. )
  2089. }
  2090. if value:
  2091. if (
  2092. content_blocks
  2093. and content_blocks[-1]["type"]
  2094. == "reasoning"
  2095. and content_blocks[-1]
  2096. .get("attributes", {})
  2097. .get("type")
  2098. == "reasoning_content"
  2099. ):
  2100. reasoning_block = content_blocks[-1]
  2101. reasoning_block["ended_at"] = time.time()
  2102. reasoning_block["duration"] = int(
  2103. reasoning_block["ended_at"]
  2104. - reasoning_block["started_at"]
  2105. )
  2106. content_blocks.append(
  2107. {
  2108. "type": "text",
  2109. "content": "",
  2110. }
  2111. )
  2112. content = f"{content}{value}"
  2113. if not content_blocks:
  2114. content_blocks.append(
  2115. {
  2116. "type": "text",
  2117. "content": "",
  2118. }
  2119. )
  2120. content_blocks[-1]["content"] = (
  2121. content_blocks[-1]["content"] + value
  2122. )
  2123. if DETECT_REASONING_TAGS:
  2124. content, content_blocks, _ = (
  2125. tag_content_handler(
  2126. "reasoning",
  2127. reasoning_tags,
  2128. content,
  2129. content_blocks,
  2130. )
  2131. )
  2132. content, content_blocks, _ = (
  2133. tag_content_handler(
  2134. "solution",
  2135. DEFAULT_SOLUTION_TAGS,
  2136. content,
  2137. content_blocks,
  2138. )
  2139. )
  2140. if DETECT_CODE_INTERPRETER:
  2141. content, content_blocks, end = (
  2142. tag_content_handler(
  2143. "code_interpreter",
  2144. DEFAULT_CODE_INTERPRETER_TAGS,
  2145. content,
  2146. content_blocks,
  2147. )
  2148. )
  2149. if end:
  2150. break
  2151. if ENABLE_REALTIME_CHAT_SAVE:
  2152. # Save message in the database
  2153. Chats.upsert_message_to_chat_by_id_and_message_id(
  2154. metadata["chat_id"],
  2155. metadata["message_id"],
  2156. {
  2157. "content": serialize_content_blocks(
  2158. content_blocks
  2159. ),
  2160. },
  2161. )
  2162. else:
  2163. data = {
  2164. "content": serialize_content_blocks(
  2165. content_blocks
  2166. ),
  2167. }
  2168. if delta:
  2169. delta_count += 1
  2170. last_delta_data = data
  2171. if delta_count >= delta_chunk_size:
  2172. await flush_pending_delta_data(delta_chunk_size)
  2173. else:
  2174. await event_emitter(
  2175. {
  2176. "type": "chat:completion",
  2177. "data": data,
  2178. }
  2179. )
  2180. except Exception as e:
  2181. done = "data: [DONE]" in line
  2182. if done:
  2183. pass
  2184. else:
  2185. log.debug(f"Error: {e}")
  2186. continue
  2187. await flush_pending_delta_data()
  2188. if content_blocks:
  2189. # Clean up the last text block
  2190. if content_blocks[-1]["type"] == "text":
  2191. content_blocks[-1]["content"] = content_blocks[-1][
  2192. "content"
  2193. ].strip()
  2194. if not content_blocks[-1]["content"]:
  2195. content_blocks.pop()
  2196. if not content_blocks:
  2197. content_blocks.append(
  2198. {
  2199. "type": "text",
  2200. "content": "",
  2201. }
  2202. )
  2203. if content_blocks[-1]["type"] == "reasoning":
  2204. reasoning_block = content_blocks[-1]
  2205. if reasoning_block.get("ended_at") is None:
  2206. reasoning_block["ended_at"] = time.time()
  2207. reasoning_block["duration"] = int(
  2208. reasoning_block["ended_at"]
  2209. - reasoning_block["started_at"]
  2210. )
  2211. if response_tool_calls:
  2212. tool_calls.append(response_tool_calls)
  2213. if response.background:
  2214. await response.background()
  2215. await stream_body_handler(response, form_data)
  2216. tool_call_retries = 0
  2217. while (
  2218. len(tool_calls) > 0
  2219. and tool_call_retries < CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES
  2220. ):
  2221. tool_call_retries += 1
  2222. response_tool_calls = tool_calls.pop(0)
  2223. content_blocks.append(
  2224. {
  2225. "type": "tool_calls",
  2226. "content": response_tool_calls,
  2227. }
  2228. )
  2229. await event_emitter(
  2230. {
  2231. "type": "chat:completion",
  2232. "data": {
  2233. "content": serialize_content_blocks(content_blocks),
  2234. },
  2235. }
  2236. )
  2237. tools = metadata.get("tools", {})
  2238. results = []
  2239. for tool_call in response_tool_calls:
  2240. print("tool_call", tool_call)
  2241. tool_call_id = tool_call.get("id", "")
  2242. tool_function_name = tool_call.get("function", {}).get(
  2243. "name", ""
  2244. )
  2245. tool_args = tool_call.get("function", {}).get("arguments", "{}")
  2246. tool_function_params = {}
  2247. try:
  2248. # json.loads cannot be used because some models do not produce valid JSON
  2249. tool_function_params = ast.literal_eval(tool_args)
  2250. except Exception as e:
  2251. log.debug(e)
  2252. # Fallback to JSON parsing
  2253. try:
  2254. tool_function_params = json.loads(tool_args)
  2255. except Exception as e:
  2256. log.error(
  2257. f"Error parsing tool call arguments: {tool_args}"
  2258. )
  2259. # Mutate the original tool call response params as they are passed back to the passed
  2260. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  2261. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  2262. # params are not valid json.
  2263. # Main case so far is no args = "" = invalid json.
  2264. log.debug(
  2265. f"Parsed args from {tool_args} to {tool_function_params}"
  2266. )
  2267. tool_call.setdefault("function", {})["arguments"] = json.dumps(
  2268. tool_function_params
  2269. )
  2270. tool_result = None
  2271. tool = None
  2272. tool_type = None
  2273. direct_tool = False
  2274. if tool_function_name in tools:
  2275. tool = tools[tool_function_name]
  2276. spec = tool.get("spec", {})
  2277. tool_type = tool.get("type", "")
  2278. direct_tool = tool.get("direct", False)
  2279. try:
  2280. allowed_params = (
  2281. spec.get("parameters", {})
  2282. .get("properties", {})
  2283. .keys()
  2284. )
  2285. tool_function_params = {
  2286. k: v
  2287. for k, v in tool_function_params.items()
  2288. if k in allowed_params
  2289. }
  2290. if direct_tool:
  2291. tool_result = await event_caller(
  2292. {
  2293. "type": "execute:tool",
  2294. "data": {
  2295. "id": str(uuid4()),
  2296. "name": tool_function_name,
  2297. "params": tool_function_params,
  2298. "server": tool.get("server", {}),
  2299. "session_id": metadata.get(
  2300. "session_id", None
  2301. ),
  2302. },
  2303. }
  2304. )
  2305. else:
  2306. tool_function = tool["callable"]
  2307. tool_result = await tool_function(
  2308. **tool_function_params
  2309. )
  2310. except Exception as e:
  2311. tool_result = str(e)
  2312. tool_result, tool_result_files, tool_result_embeds = (
  2313. process_tool_result(
  2314. request,
  2315. tool_function_name,
  2316. tool_result,
  2317. tool_type,
  2318. direct_tool,
  2319. metadata,
  2320. user,
  2321. )
  2322. )
  2323. results.append(
  2324. {
  2325. "tool_call_id": tool_call_id,
  2326. "content": tool_result or "",
  2327. **(
  2328. {"files": tool_result_files}
  2329. if tool_result_files
  2330. else {}
  2331. ),
  2332. **(
  2333. {"embeds": tool_result_embeds}
  2334. if tool_result_embeds
  2335. else {}
  2336. ),
  2337. }
  2338. )
  2339. content_blocks[-1]["results"] = results
  2340. content_blocks.append(
  2341. {
  2342. "type": "text",
  2343. "content": "",
  2344. }
  2345. )
  2346. await event_emitter(
  2347. {
  2348. "type": "chat:completion",
  2349. "data": {
  2350. "content": serialize_content_blocks(content_blocks),
  2351. },
  2352. }
  2353. )
  2354. try:
  2355. new_form_data = {
  2356. "model": model_id,
  2357. "stream": True,
  2358. "tools": form_data["tools"],
  2359. "messages": [
  2360. *form_data["messages"],
  2361. *convert_content_blocks_to_messages(
  2362. content_blocks, True
  2363. ),
  2364. ],
  2365. }
  2366. res = await generate_chat_completion(
  2367. request,
  2368. new_form_data,
  2369. user,
  2370. )
  2371. if isinstance(res, StreamingResponse):
  2372. await stream_body_handler(res, new_form_data)
  2373. else:
  2374. break
  2375. except Exception as e:
  2376. log.debug(e)
  2377. break
  2378. if DETECT_CODE_INTERPRETER:
  2379. MAX_RETRIES = 5
  2380. retries = 0
  2381. while (
  2382. content_blocks[-1]["type"] == "code_interpreter"
  2383. and retries < MAX_RETRIES
  2384. ):
  2385. await event_emitter(
  2386. {
  2387. "type": "chat:completion",
  2388. "data": {
  2389. "content": serialize_content_blocks(content_blocks),
  2390. },
  2391. }
  2392. )
  2393. retries += 1
  2394. log.debug(f"Attempt count: {retries}")
  2395. output = ""
  2396. try:
  2397. if content_blocks[-1]["attributes"].get("type") == "code":
  2398. code = content_blocks[-1]["content"]
  2399. if CODE_INTERPRETER_BLOCKED_MODULES:
  2400. blocking_code = textwrap.dedent(
  2401. f"""
  2402. import builtins
  2403. BLOCKED_MODULES = {CODE_INTERPRETER_BLOCKED_MODULES}
  2404. _real_import = builtins.__import__
  2405. def restricted_import(name, globals=None, locals=None, fromlist=(), level=0):
  2406. if name.split('.')[0] in BLOCKED_MODULES:
  2407. importer_name = globals.get('__name__') if globals else None
  2408. if importer_name == '__main__':
  2409. raise ImportError(
  2410. f"Direct import of module {{name}} is restricted."
  2411. )
  2412. return _real_import(name, globals, locals, fromlist, level)
  2413. builtins.__import__ = restricted_import
  2414. """
  2415. )
  2416. code = blocking_code + "\n" + code
  2417. if (
  2418. request.app.state.config.CODE_INTERPRETER_ENGINE
  2419. == "pyodide"
  2420. ):
  2421. output = await event_caller(
  2422. {
  2423. "type": "execute:python",
  2424. "data": {
  2425. "id": str(uuid4()),
  2426. "code": code,
  2427. "session_id": metadata.get(
  2428. "session_id", None
  2429. ),
  2430. },
  2431. }
  2432. )
  2433. elif (
  2434. request.app.state.config.CODE_INTERPRETER_ENGINE
  2435. == "jupyter"
  2436. ):
  2437. output = await execute_code_jupyter(
  2438. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  2439. code,
  2440. (
  2441. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  2442. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2443. == "token"
  2444. else None
  2445. ),
  2446. (
  2447. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  2448. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2449. == "password"
  2450. else None
  2451. ),
  2452. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  2453. )
  2454. else:
  2455. output = {
  2456. "stdout": "Code interpreter engine not configured."
  2457. }
  2458. log.debug(f"Code interpreter output: {output}")
  2459. if isinstance(output, dict):
  2460. stdout = output.get("stdout", "")
  2461. if isinstance(stdout, str):
  2462. stdoutLines = stdout.split("\n")
  2463. for idx, line in enumerate(stdoutLines):
  2464. if "data:image/png;base64" in line:
  2465. image_url = get_image_url_from_base64(
  2466. request,
  2467. line,
  2468. metadata,
  2469. user,
  2470. )
  2471. if image_url:
  2472. stdoutLines[idx] = (
  2473. f"![Output Image]({image_url})"
  2474. )
  2475. output["stdout"] = "\n".join(stdoutLines)
  2476. result = output.get("result", "")
  2477. if isinstance(result, str):
  2478. resultLines = result.split("\n")
  2479. for idx, line in enumerate(resultLines):
  2480. if "data:image/png;base64" in line:
  2481. image_url = get_image_url_from_base64(
  2482. request,
  2483. line,
  2484. metadata,
  2485. user,
  2486. )
  2487. resultLines[idx] = (
  2488. f"![Output Image]({image_url})"
  2489. )
  2490. output["result"] = "\n".join(resultLines)
  2491. except Exception as e:
  2492. output = str(e)
  2493. content_blocks[-1]["output"] = output
  2494. content_blocks.append(
  2495. {
  2496. "type": "text",
  2497. "content": "",
  2498. }
  2499. )
  2500. await event_emitter(
  2501. {
  2502. "type": "chat:completion",
  2503. "data": {
  2504. "content": serialize_content_blocks(content_blocks),
  2505. },
  2506. }
  2507. )
  2508. try:
  2509. new_form_data = {
  2510. "model": model_id,
  2511. "stream": True,
  2512. "messages": [
  2513. *form_data["messages"],
  2514. {
  2515. "role": "assistant",
  2516. "content": serialize_content_blocks(
  2517. content_blocks, raw=True
  2518. ),
  2519. },
  2520. ],
  2521. }
  2522. res = await generate_chat_completion(
  2523. request,
  2524. new_form_data,
  2525. user,
  2526. )
  2527. if isinstance(res, StreamingResponse):
  2528. await stream_body_handler(res, new_form_data)
  2529. else:
  2530. break
  2531. except Exception as e:
  2532. log.debug(e)
  2533. break
  2534. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  2535. data = {
  2536. "done": True,
  2537. "content": serialize_content_blocks(content_blocks),
  2538. "title": title,
  2539. }
  2540. if not ENABLE_REALTIME_CHAT_SAVE:
  2541. # Save message in the database
  2542. Chats.upsert_message_to_chat_by_id_and_message_id(
  2543. metadata["chat_id"],
  2544. metadata["message_id"],
  2545. {
  2546. "content": serialize_content_blocks(content_blocks),
  2547. },
  2548. )
  2549. # Send a webhook notification if the user is not active
  2550. if not get_active_status_by_user_id(user.id):
  2551. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  2552. if webhook_url:
  2553. await post_webhook(
  2554. request.app.state.WEBUI_NAME,
  2555. webhook_url,
  2556. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  2557. {
  2558. "action": "chat",
  2559. "message": content,
  2560. "title": title,
  2561. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  2562. },
  2563. )
  2564. await event_emitter(
  2565. {
  2566. "type": "chat:completion",
  2567. "data": data,
  2568. }
  2569. )
  2570. await background_tasks_handler()
  2571. except asyncio.CancelledError:
  2572. log.warning("Task was cancelled!")
  2573. await event_emitter({"type": "chat:tasks:cancel"})
  2574. if not ENABLE_REALTIME_CHAT_SAVE:
  2575. # Save message in the database
  2576. Chats.upsert_message_to_chat_by_id_and_message_id(
  2577. metadata["chat_id"],
  2578. metadata["message_id"],
  2579. {
  2580. "content": serialize_content_blocks(content_blocks),
  2581. },
  2582. )
  2583. if response.background is not None:
  2584. await response.background()
  2585. return await response_handler(response, events)
  2586. else:
  2587. # Fallback to the original response
  2588. async def stream_wrapper(original_generator, events):
  2589. def wrap_item(item):
  2590. return f"data: {item}\n\n"
  2591. for event in events:
  2592. event, _ = await process_filter_functions(
  2593. request=request,
  2594. filter_functions=filter_functions,
  2595. filter_type="stream",
  2596. form_data=event,
  2597. extra_params=extra_params,
  2598. )
  2599. if event:
  2600. yield wrap_item(json.dumps(event))
  2601. async for data in original_generator:
  2602. data, _ = await process_filter_functions(
  2603. request=request,
  2604. filter_functions=filter_functions,
  2605. filter_type="stream",
  2606. form_data=data,
  2607. extra_params=extra_params,
  2608. )
  2609. if data:
  2610. yield data
  2611. return StreamingResponse(
  2612. stream_wrapper(response.body_iterator, events),
  2613. headers=dict(response.headers),
  2614. background=response.background,
  2615. )