middleware.py 126 KB

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