middleware.py 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105
  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[f"{server_id}_{tool_spec['name']}"] = {
  1003. "spec": {
  1004. **tool_spec,
  1005. "name": f"{server_id}_{tool_spec['name']}",
  1006. },
  1007. "callable": tool_function,
  1008. "type": "mcp",
  1009. "client": mcp_client,
  1010. "direct": False,
  1011. }
  1012. mcp_clients.append(mcp_client)
  1013. except Exception as e:
  1014. log.debug(e)
  1015. continue
  1016. tools_dict = await get_tools(
  1017. request,
  1018. tool_ids,
  1019. user,
  1020. {
  1021. **extra_params,
  1022. "__model__": models[task_model_id],
  1023. "__messages__": form_data["messages"],
  1024. "__files__": metadata.get("files", []),
  1025. },
  1026. )
  1027. if mcp_tools_dict:
  1028. tools_dict = {**tools_dict, **mcp_tools_dict}
  1029. if direct_tool_servers:
  1030. for tool_server in direct_tool_servers:
  1031. tool_specs = tool_server.pop("specs", [])
  1032. for tool in tool_specs:
  1033. tools_dict[tool["name"]] = {
  1034. "spec": tool,
  1035. "direct": True,
  1036. "server": tool_server,
  1037. }
  1038. if mcp_clients:
  1039. metadata["mcp_clients"] = mcp_clients
  1040. if tools_dict:
  1041. if metadata.get("params", {}).get("function_calling") == "native":
  1042. # If the function calling is native, then call the tools function calling handler
  1043. metadata["tools"] = tools_dict
  1044. form_data["tools"] = [
  1045. {"type": "function", "function": tool.get("spec", {})}
  1046. for tool in tools_dict.values()
  1047. ]
  1048. else:
  1049. # If the function calling is not native, then call the tools function calling handler
  1050. try:
  1051. form_data, flags = await chat_completion_tools_handler(
  1052. request, form_data, extra_params, user, models, tools_dict
  1053. )
  1054. sources.extend(flags.get("sources", []))
  1055. except Exception as e:
  1056. log.exception(e)
  1057. try:
  1058. form_data, flags = await chat_completion_files_handler(
  1059. request, form_data, extra_params, user
  1060. )
  1061. sources.extend(flags.get("sources", []))
  1062. except Exception as e:
  1063. log.exception(e)
  1064. # If context is not empty, insert it into the messages
  1065. if len(sources) > 0:
  1066. context_string = ""
  1067. citation_idx_map = {}
  1068. for source in sources:
  1069. is_tool_result = source.get("tool_result", False)
  1070. if "document" in source and not is_tool_result:
  1071. for document_text, document_metadata in zip(
  1072. source["document"], source["metadata"]
  1073. ):
  1074. source_name = source.get("source", {}).get("name", None)
  1075. source_id = (
  1076. document_metadata.get("source", None)
  1077. or source.get("source", {}).get("id", None)
  1078. or "N/A"
  1079. )
  1080. if source_id not in citation_idx_map:
  1081. citation_idx_map[source_id] = len(citation_idx_map) + 1
  1082. context_string += (
  1083. f'<source id="{citation_idx_map[source_id]}"'
  1084. + (f' name="{source_name}"' if source_name else "")
  1085. + f">{document_text}</source>\n"
  1086. )
  1087. context_string = context_string.strip()
  1088. prompt = get_last_user_message(form_data["messages"])
  1089. if prompt is None:
  1090. raise Exception("No user message found")
  1091. if context_string != "":
  1092. form_data["messages"] = add_or_update_user_message(
  1093. rag_template(
  1094. request.app.state.config.RAG_TEMPLATE,
  1095. context_string,
  1096. prompt,
  1097. ),
  1098. form_data["messages"],
  1099. append=False,
  1100. )
  1101. # If there are citations, add them to the data_items
  1102. sources = [
  1103. source
  1104. for source in sources
  1105. if source.get("source", {}).get("name", "")
  1106. or source.get("source", {}).get("id", "")
  1107. ]
  1108. if len(sources) > 0:
  1109. events.append({"sources": sources})
  1110. if model_knowledge:
  1111. await event_emitter(
  1112. {
  1113. "type": "status",
  1114. "data": {
  1115. "action": "knowledge_search",
  1116. "query": user_message,
  1117. "done": True,
  1118. "hidden": True,
  1119. },
  1120. }
  1121. )
  1122. return form_data, metadata, events
  1123. async def process_chat_response(
  1124. request, response, form_data, user, metadata, model, events, tasks
  1125. ):
  1126. async def background_tasks_handler():
  1127. messages_map = Chats.get_messages_map_by_chat_id(metadata["chat_id"])
  1128. message = messages_map.get(metadata["message_id"]) if messages_map else None
  1129. if message:
  1130. message_list = get_message_list(messages_map, metadata["message_id"])
  1131. # Remove details tags and files from the messages.
  1132. # as get_message_list creates a new list, it does not affect
  1133. # the original messages outside of this handler
  1134. messages = []
  1135. for message in message_list:
  1136. content = message.get("content", "")
  1137. if isinstance(content, list):
  1138. for item in content:
  1139. if item.get("type") == "text":
  1140. content = item["text"]
  1141. break
  1142. if isinstance(content, str):
  1143. content = re.sub(
  1144. r"<details\b[^>]*>.*?<\/details>|!\[.*?\]\(.*?\)",
  1145. "",
  1146. content,
  1147. flags=re.S | re.I,
  1148. ).strip()
  1149. messages.append(
  1150. {
  1151. **message,
  1152. "role": message.get(
  1153. "role", "assistant"
  1154. ), # Safe fallback for missing role
  1155. "content": content,
  1156. }
  1157. )
  1158. if tasks and messages:
  1159. if (
  1160. TASKS.FOLLOW_UP_GENERATION in tasks
  1161. and tasks[TASKS.FOLLOW_UP_GENERATION]
  1162. ):
  1163. res = await generate_follow_ups(
  1164. request,
  1165. {
  1166. "model": message["model"],
  1167. "messages": messages,
  1168. "message_id": metadata["message_id"],
  1169. "chat_id": metadata["chat_id"],
  1170. },
  1171. user,
  1172. )
  1173. if res and isinstance(res, dict):
  1174. if len(res.get("choices", [])) == 1:
  1175. follow_ups_string = (
  1176. res.get("choices", [])[0]
  1177. .get("message", {})
  1178. .get("content", "")
  1179. )
  1180. else:
  1181. follow_ups_string = ""
  1182. follow_ups_string = follow_ups_string[
  1183. follow_ups_string.find("{") : follow_ups_string.rfind("}")
  1184. + 1
  1185. ]
  1186. try:
  1187. follow_ups = json.loads(follow_ups_string).get(
  1188. "follow_ups", []
  1189. )
  1190. Chats.upsert_message_to_chat_by_id_and_message_id(
  1191. metadata["chat_id"],
  1192. metadata["message_id"],
  1193. {
  1194. "followUps": follow_ups,
  1195. },
  1196. )
  1197. await event_emitter(
  1198. {
  1199. "type": "chat:message:follow_ups",
  1200. "data": {
  1201. "follow_ups": follow_ups,
  1202. },
  1203. }
  1204. )
  1205. except Exception as e:
  1206. pass
  1207. if TASKS.TITLE_GENERATION in tasks:
  1208. user_message = get_last_user_message(messages)
  1209. if user_message and len(user_message) > 100:
  1210. user_message = user_message[:100] + "..."
  1211. if tasks[TASKS.TITLE_GENERATION]:
  1212. res = await generate_title(
  1213. request,
  1214. {
  1215. "model": message["model"],
  1216. "messages": messages,
  1217. "chat_id": metadata["chat_id"],
  1218. },
  1219. user,
  1220. )
  1221. if res and isinstance(res, dict):
  1222. if len(res.get("choices", [])) == 1:
  1223. title_string = (
  1224. res.get("choices", [])[0]
  1225. .get("message", {})
  1226. .get(
  1227. "content", message.get("content", user_message)
  1228. )
  1229. )
  1230. else:
  1231. title_string = ""
  1232. title_string = title_string[
  1233. title_string.find("{") : title_string.rfind("}") + 1
  1234. ]
  1235. try:
  1236. title = json.loads(title_string).get(
  1237. "title", user_message
  1238. )
  1239. except Exception as e:
  1240. title = ""
  1241. if not title:
  1242. title = messages[0].get("content", user_message)
  1243. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1244. await event_emitter(
  1245. {
  1246. "type": "chat:title",
  1247. "data": title,
  1248. }
  1249. )
  1250. elif len(messages) == 2:
  1251. title = messages[0].get("content", user_message)
  1252. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1253. await event_emitter(
  1254. {
  1255. "type": "chat:title",
  1256. "data": message.get("content", user_message),
  1257. }
  1258. )
  1259. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  1260. res = await generate_chat_tags(
  1261. request,
  1262. {
  1263. "model": message["model"],
  1264. "messages": messages,
  1265. "chat_id": metadata["chat_id"],
  1266. },
  1267. user,
  1268. )
  1269. if res and isinstance(res, dict):
  1270. if len(res.get("choices", [])) == 1:
  1271. tags_string = (
  1272. res.get("choices", [])[0]
  1273. .get("message", {})
  1274. .get("content", "")
  1275. )
  1276. else:
  1277. tags_string = ""
  1278. tags_string = tags_string[
  1279. tags_string.find("{") : tags_string.rfind("}") + 1
  1280. ]
  1281. try:
  1282. tags = json.loads(tags_string).get("tags", [])
  1283. Chats.update_chat_tags_by_id(
  1284. metadata["chat_id"], tags, user
  1285. )
  1286. await event_emitter(
  1287. {
  1288. "type": "chat:tags",
  1289. "data": tags,
  1290. }
  1291. )
  1292. except Exception as e:
  1293. pass
  1294. event_emitter = None
  1295. event_caller = None
  1296. if (
  1297. "session_id" in metadata
  1298. and metadata["session_id"]
  1299. and "chat_id" in metadata
  1300. and metadata["chat_id"]
  1301. and "message_id" in metadata
  1302. and metadata["message_id"]
  1303. ):
  1304. event_emitter = get_event_emitter(metadata)
  1305. event_caller = get_event_call(metadata)
  1306. # Non-streaming response
  1307. if not isinstance(response, StreamingResponse):
  1308. if event_emitter:
  1309. try:
  1310. if isinstance(response, dict) or isinstance(response, JSONResponse):
  1311. if isinstance(response, list) and len(response) == 1:
  1312. # If the response is a single-item list, unwrap it #17213
  1313. response = response[0]
  1314. if isinstance(response, JSONResponse) and isinstance(
  1315. response.body, bytes
  1316. ):
  1317. try:
  1318. response_data = json.loads(response.body.decode("utf-8"))
  1319. except json.JSONDecodeError:
  1320. response_data = {
  1321. "error": {"detail": "Invalid JSON response"}
  1322. }
  1323. else:
  1324. response_data = response
  1325. if "error" in response_data:
  1326. error = response_data.get("error")
  1327. if isinstance(error, dict):
  1328. error = error.get("detail", error)
  1329. else:
  1330. error = str(error)
  1331. Chats.upsert_message_to_chat_by_id_and_message_id(
  1332. metadata["chat_id"],
  1333. metadata["message_id"],
  1334. {
  1335. "error": {"content": error},
  1336. },
  1337. )
  1338. if isinstance(error, str) or isinstance(error, dict):
  1339. await event_emitter(
  1340. {
  1341. "type": "chat:message:error",
  1342. "data": {"error": {"content": error}},
  1343. }
  1344. )
  1345. if "selected_model_id" in response_data:
  1346. Chats.upsert_message_to_chat_by_id_and_message_id(
  1347. metadata["chat_id"],
  1348. metadata["message_id"],
  1349. {
  1350. "selectedModelId": response_data["selected_model_id"],
  1351. },
  1352. )
  1353. choices = response_data.get("choices", [])
  1354. if choices and choices[0].get("message", {}).get("content"):
  1355. content = response_data["choices"][0]["message"]["content"]
  1356. if content:
  1357. await event_emitter(
  1358. {
  1359. "type": "chat:completion",
  1360. "data": response_data,
  1361. }
  1362. )
  1363. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1364. await event_emitter(
  1365. {
  1366. "type": "chat:completion",
  1367. "data": {
  1368. "done": True,
  1369. "content": content,
  1370. "title": title,
  1371. },
  1372. }
  1373. )
  1374. # Save message in the database
  1375. Chats.upsert_message_to_chat_by_id_and_message_id(
  1376. metadata["chat_id"],
  1377. metadata["message_id"],
  1378. {
  1379. "role": "assistant",
  1380. "content": content,
  1381. },
  1382. )
  1383. # Send a webhook notification if the user is not active
  1384. if not get_active_status_by_user_id(user.id):
  1385. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1386. if webhook_url:
  1387. await post_webhook(
  1388. request.app.state.WEBUI_NAME,
  1389. webhook_url,
  1390. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1391. {
  1392. "action": "chat",
  1393. "message": content,
  1394. "title": title,
  1395. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1396. },
  1397. )
  1398. await background_tasks_handler()
  1399. if events and isinstance(events, list):
  1400. extra_response = {}
  1401. for event in events:
  1402. if isinstance(event, dict):
  1403. extra_response.update(event)
  1404. else:
  1405. extra_response[event] = True
  1406. response_data = {
  1407. **extra_response,
  1408. **response_data,
  1409. }
  1410. if isinstance(response, dict):
  1411. response = response_data
  1412. if isinstance(response, JSONResponse):
  1413. response = JSONResponse(
  1414. content=response_data,
  1415. headers=response.headers,
  1416. status_code=response.status_code,
  1417. )
  1418. except Exception as e:
  1419. log.debug(f"Error occurred while processing request: {e}")
  1420. pass
  1421. return response
  1422. else:
  1423. if events and isinstance(events, list) and isinstance(response, dict):
  1424. extra_response = {}
  1425. for event in events:
  1426. if isinstance(event, dict):
  1427. extra_response.update(event)
  1428. else:
  1429. extra_response[event] = True
  1430. response = {
  1431. **extra_response,
  1432. **response,
  1433. }
  1434. return response
  1435. # Non standard response
  1436. if not any(
  1437. content_type in response.headers["Content-Type"]
  1438. for content_type in ["text/event-stream", "application/x-ndjson"]
  1439. ):
  1440. return response
  1441. oauth_token = None
  1442. try:
  1443. if request.cookies.get("oauth_session_id", None):
  1444. oauth_token = await request.app.state.oauth_manager.get_oauth_token(
  1445. user.id,
  1446. request.cookies.get("oauth_session_id", None),
  1447. )
  1448. except Exception as e:
  1449. log.error(f"Error getting OAuth token: {e}")
  1450. extra_params = {
  1451. "__event_emitter__": event_emitter,
  1452. "__event_call__": event_caller,
  1453. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  1454. "__metadata__": metadata,
  1455. "__oauth_token__": oauth_token,
  1456. "__request__": request,
  1457. "__model__": model,
  1458. }
  1459. filter_functions = [
  1460. Functions.get_function_by_id(filter_id)
  1461. for filter_id in get_sorted_filter_ids(
  1462. request, model, metadata.get("filter_ids", [])
  1463. )
  1464. ]
  1465. # Streaming response
  1466. if event_emitter and event_caller:
  1467. task_id = str(uuid4()) # Create a unique task ID.
  1468. model_id = form_data.get("model", "")
  1469. def split_content_and_whitespace(content):
  1470. content_stripped = content.rstrip()
  1471. original_whitespace = (
  1472. content[len(content_stripped) :]
  1473. if len(content) > len(content_stripped)
  1474. else ""
  1475. )
  1476. return content_stripped, original_whitespace
  1477. def is_opening_code_block(content):
  1478. backtick_segments = content.split("```")
  1479. # Even number of segments means the last backticks are opening a new block
  1480. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  1481. # Handle as a background task
  1482. async def response_handler(response, events):
  1483. def serialize_content_blocks(content_blocks, raw=False):
  1484. content = ""
  1485. for block in content_blocks:
  1486. if block["type"] == "text":
  1487. block_content = block["content"].strip()
  1488. if block_content:
  1489. content = f"{content}{block_content}\n"
  1490. elif block["type"] == "tool_calls":
  1491. attributes = block.get("attributes", {})
  1492. tool_calls = block.get("content", [])
  1493. results = block.get("results", [])
  1494. if content and not content.endswith("\n"):
  1495. content += "\n"
  1496. if results:
  1497. tool_calls_display_content = ""
  1498. for tool_call in tool_calls:
  1499. tool_call_id = tool_call.get("id", "")
  1500. tool_name = tool_call.get("function", {}).get(
  1501. "name", ""
  1502. )
  1503. tool_arguments = tool_call.get("function", {}).get(
  1504. "arguments", ""
  1505. )
  1506. tool_result = None
  1507. tool_result_files = None
  1508. for result in results:
  1509. if tool_call_id == result.get("tool_call_id", ""):
  1510. tool_result = result.get("content", None)
  1511. tool_result_files = result.get("files", None)
  1512. break
  1513. if tool_result is not None:
  1514. tool_result_embeds = result.get("embeds", "")
  1515. 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'
  1516. else:
  1517. 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'
  1518. if not raw:
  1519. content = f"{content}{tool_calls_display_content}"
  1520. else:
  1521. tool_calls_display_content = ""
  1522. for tool_call in tool_calls:
  1523. tool_call_id = tool_call.get("id", "")
  1524. tool_name = tool_call.get("function", {}).get(
  1525. "name", ""
  1526. )
  1527. tool_arguments = tool_call.get("function", {}).get(
  1528. "arguments", ""
  1529. )
  1530. 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'
  1531. if not raw:
  1532. content = f"{content}{tool_calls_display_content}"
  1533. elif block["type"] == "reasoning":
  1534. reasoning_display_content = "\n".join(
  1535. (f"> {line}" if not line.startswith(">") else line)
  1536. for line in block["content"].splitlines()
  1537. )
  1538. reasoning_duration = block.get("duration", None)
  1539. start_tag = block.get("start_tag", "")
  1540. end_tag = block.get("end_tag", "")
  1541. if content and not content.endswith("\n"):
  1542. content += "\n"
  1543. if reasoning_duration is not None:
  1544. if raw:
  1545. content = (
  1546. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1547. )
  1548. else:
  1549. 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'
  1550. else:
  1551. if raw:
  1552. content = (
  1553. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1554. )
  1555. else:
  1556. content = f'{content}<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1557. elif block["type"] == "code_interpreter":
  1558. attributes = block.get("attributes", {})
  1559. output = block.get("output", None)
  1560. lang = attributes.get("lang", "")
  1561. content_stripped, original_whitespace = (
  1562. split_content_and_whitespace(content)
  1563. )
  1564. if is_opening_code_block(content_stripped):
  1565. # Remove trailing backticks that would open a new block
  1566. content = (
  1567. content_stripped.rstrip("`").rstrip()
  1568. + original_whitespace
  1569. )
  1570. else:
  1571. # Keep content as is - either closing backticks or no backticks
  1572. content = content_stripped + original_whitespace
  1573. if content and not content.endswith("\n"):
  1574. content += "\n"
  1575. if output:
  1576. output = html.escape(json.dumps(output))
  1577. if raw:
  1578. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1579. else:
  1580. content = f'{content}<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1581. else:
  1582. if raw:
  1583. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1584. else:
  1585. content = f'{content}<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1586. else:
  1587. block_content = str(block["content"]).strip()
  1588. if block_content:
  1589. content = f"{content}{block['type']}: {block_content}\n"
  1590. return content.strip()
  1591. def convert_content_blocks_to_messages(content_blocks, raw=False):
  1592. messages = []
  1593. temp_blocks = []
  1594. for idx, block in enumerate(content_blocks):
  1595. if block["type"] == "tool_calls":
  1596. messages.append(
  1597. {
  1598. "role": "assistant",
  1599. "content": serialize_content_blocks(temp_blocks, raw),
  1600. "tool_calls": block.get("content"),
  1601. }
  1602. )
  1603. results = block.get("results", [])
  1604. for result in results:
  1605. messages.append(
  1606. {
  1607. "role": "tool",
  1608. "tool_call_id": result["tool_call_id"],
  1609. "content": result.get("content", "") or "",
  1610. }
  1611. )
  1612. temp_blocks = []
  1613. else:
  1614. temp_blocks.append(block)
  1615. if temp_blocks:
  1616. content = serialize_content_blocks(temp_blocks, raw)
  1617. if content:
  1618. messages.append(
  1619. {
  1620. "role": "assistant",
  1621. "content": content,
  1622. }
  1623. )
  1624. return messages
  1625. def tag_content_handler(content_type, tags, content, content_blocks):
  1626. end_flag = False
  1627. def extract_attributes(tag_content):
  1628. """Extract attributes from a tag if they exist."""
  1629. attributes = {}
  1630. if not tag_content: # Ensure tag_content is not None
  1631. return attributes
  1632. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1633. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1634. for key, value in matches:
  1635. attributes[key] = value
  1636. return attributes
  1637. if content_blocks[-1]["type"] == "text":
  1638. for start_tag, end_tag in tags:
  1639. start_tag_pattern = rf"{re.escape(start_tag)}"
  1640. if start_tag.startswith("<") and start_tag.endswith(">"):
  1641. # Match start tag e.g., <tag> or <tag attr="value">
  1642. # remove both '<' and '>' from start_tag
  1643. # Match start tag with attributes
  1644. start_tag_pattern = (
  1645. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1646. )
  1647. match = re.search(start_tag_pattern, content)
  1648. if match:
  1649. try:
  1650. attr_content = (
  1651. match.group(1) if match.group(1) else ""
  1652. ) # Ensure it's not None
  1653. except:
  1654. attr_content = ""
  1655. attributes = extract_attributes(
  1656. attr_content
  1657. ) # Extract attributes safely
  1658. # Capture everything before and after the matched tag
  1659. before_tag = content[
  1660. : match.start()
  1661. ] # Content before opening tag
  1662. after_tag = content[
  1663. match.end() :
  1664. ] # Content after opening tag
  1665. # Remove the start tag and after from the currently handling text block
  1666. content_blocks[-1]["content"] = content_blocks[-1][
  1667. "content"
  1668. ].replace(match.group(0) + after_tag, "")
  1669. if before_tag:
  1670. content_blocks[-1]["content"] = before_tag
  1671. if not content_blocks[-1]["content"]:
  1672. content_blocks.pop()
  1673. # Append the new block
  1674. content_blocks.append(
  1675. {
  1676. "type": content_type,
  1677. "start_tag": start_tag,
  1678. "end_tag": end_tag,
  1679. "attributes": attributes,
  1680. "content": "",
  1681. "started_at": time.time(),
  1682. }
  1683. )
  1684. if after_tag:
  1685. content_blocks[-1]["content"] = after_tag
  1686. tag_content_handler(
  1687. content_type, tags, after_tag, content_blocks
  1688. )
  1689. break
  1690. elif content_blocks[-1]["type"] == content_type:
  1691. start_tag = content_blocks[-1]["start_tag"]
  1692. end_tag = content_blocks[-1]["end_tag"]
  1693. if end_tag.startswith("<") and end_tag.endswith(">"):
  1694. # Match end tag e.g., </tag>
  1695. end_tag_pattern = rf"{re.escape(end_tag)}"
  1696. else:
  1697. # Handle cases where end_tag is just a tag name
  1698. end_tag_pattern = rf"{re.escape(end_tag)}"
  1699. # Check if the content has the end tag
  1700. if re.search(end_tag_pattern, content):
  1701. end_flag = True
  1702. block_content = content_blocks[-1]["content"]
  1703. # Strip start and end tags from the content
  1704. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1705. block_content = re.sub(
  1706. start_tag_pattern, "", block_content
  1707. ).strip()
  1708. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1709. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1710. # Content inside the tag
  1711. block_content = (
  1712. split_content[0].strip() if split_content else ""
  1713. )
  1714. # Leftover content (everything after `</tag>`)
  1715. leftover_content = (
  1716. split_content[1].strip() if len(split_content) > 1 else ""
  1717. )
  1718. if block_content:
  1719. content_blocks[-1]["content"] = block_content
  1720. content_blocks[-1]["ended_at"] = time.time()
  1721. content_blocks[-1]["duration"] = int(
  1722. content_blocks[-1]["ended_at"]
  1723. - content_blocks[-1]["started_at"]
  1724. )
  1725. # Reset the content_blocks by appending a new text block
  1726. if content_type != "code_interpreter":
  1727. if leftover_content:
  1728. content_blocks.append(
  1729. {
  1730. "type": "text",
  1731. "content": leftover_content,
  1732. }
  1733. )
  1734. else:
  1735. content_blocks.append(
  1736. {
  1737. "type": "text",
  1738. "content": "",
  1739. }
  1740. )
  1741. else:
  1742. # Remove the block if content is empty
  1743. content_blocks.pop()
  1744. if leftover_content:
  1745. content_blocks.append(
  1746. {
  1747. "type": "text",
  1748. "content": leftover_content,
  1749. }
  1750. )
  1751. else:
  1752. content_blocks.append(
  1753. {
  1754. "type": "text",
  1755. "content": "",
  1756. }
  1757. )
  1758. # Clean processed content
  1759. start_tag_pattern = rf"{re.escape(start_tag)}"
  1760. if start_tag.startswith("<") and start_tag.endswith(">"):
  1761. # Match start tag e.g., <tag> or <tag attr="value">
  1762. # remove both '<' and '>' from start_tag
  1763. # Match start tag with attributes
  1764. start_tag_pattern = (
  1765. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1766. )
  1767. content = re.sub(
  1768. rf"{start_tag_pattern}(.|\n)*?{re.escape(end_tag)}",
  1769. "",
  1770. content,
  1771. flags=re.DOTALL,
  1772. )
  1773. return content, content_blocks, end_flag
  1774. message = Chats.get_message_by_id_and_message_id(
  1775. metadata["chat_id"], metadata["message_id"]
  1776. )
  1777. tool_calls = []
  1778. last_assistant_message = None
  1779. try:
  1780. if form_data["messages"][-1]["role"] == "assistant":
  1781. last_assistant_message = get_last_assistant_message(
  1782. form_data["messages"]
  1783. )
  1784. except Exception as e:
  1785. pass
  1786. content = (
  1787. message.get("content", "")
  1788. if message
  1789. else last_assistant_message if last_assistant_message else ""
  1790. )
  1791. content_blocks = [
  1792. {
  1793. "type": "text",
  1794. "content": content,
  1795. }
  1796. ]
  1797. reasoning_tags_param = metadata.get("params", {}).get("reasoning_tags")
  1798. DETECT_REASONING_TAGS = reasoning_tags_param is not False
  1799. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1800. "code_interpreter", False
  1801. )
  1802. reasoning_tags = []
  1803. if DETECT_REASONING_TAGS:
  1804. if (
  1805. isinstance(reasoning_tags_param, list)
  1806. and len(reasoning_tags_param) == 2
  1807. ):
  1808. reasoning_tags = [
  1809. (reasoning_tags_param[0], reasoning_tags_param[1])
  1810. ]
  1811. else:
  1812. reasoning_tags = DEFAULT_REASONING_TAGS
  1813. try:
  1814. for event in events:
  1815. await event_emitter(
  1816. {
  1817. "type": "chat:completion",
  1818. "data": event,
  1819. }
  1820. )
  1821. # Save message in the database
  1822. Chats.upsert_message_to_chat_by_id_and_message_id(
  1823. metadata["chat_id"],
  1824. metadata["message_id"],
  1825. {
  1826. **event,
  1827. },
  1828. )
  1829. async def stream_body_handler(response, form_data):
  1830. nonlocal content
  1831. nonlocal content_blocks
  1832. response_tool_calls = []
  1833. delta_count = 0
  1834. delta_chunk_size = max(
  1835. CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
  1836. int(
  1837. metadata.get("params", {}).get("stream_delta_chunk_size")
  1838. or 1
  1839. ),
  1840. )
  1841. last_delta_data = None
  1842. async def flush_pending_delta_data(threshold: int = 0):
  1843. nonlocal delta_count
  1844. nonlocal last_delta_data
  1845. if delta_count >= threshold and last_delta_data:
  1846. await event_emitter(
  1847. {
  1848. "type": "chat:completion",
  1849. "data": last_delta_data,
  1850. }
  1851. )
  1852. delta_count = 0
  1853. last_delta_data = None
  1854. async for line in response.body_iterator:
  1855. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1856. data = line
  1857. # Skip empty lines
  1858. if not data.strip():
  1859. continue
  1860. # "data:" is the prefix for each event
  1861. if not data.startswith("data:"):
  1862. continue
  1863. # Remove the prefix
  1864. data = data[len("data:") :].strip()
  1865. try:
  1866. data = json.loads(data)
  1867. data, _ = await process_filter_functions(
  1868. request=request,
  1869. filter_functions=filter_functions,
  1870. filter_type="stream",
  1871. form_data=data,
  1872. extra_params={"__body__": form_data, **extra_params},
  1873. )
  1874. if data:
  1875. if "event" in data:
  1876. await event_emitter(data.get("event", {}))
  1877. if "selected_model_id" in data:
  1878. model_id = data["selected_model_id"]
  1879. Chats.upsert_message_to_chat_by_id_and_message_id(
  1880. metadata["chat_id"],
  1881. metadata["message_id"],
  1882. {
  1883. "selectedModelId": model_id,
  1884. },
  1885. )
  1886. await event_emitter(
  1887. {
  1888. "type": "chat:completion",
  1889. "data": data,
  1890. }
  1891. )
  1892. else:
  1893. choices = data.get("choices", [])
  1894. # 17421
  1895. usage = data.get("usage", {}) or {}
  1896. usage.update(data.get("timings", {})) # llama.cpp
  1897. if usage:
  1898. await event_emitter(
  1899. {
  1900. "type": "chat:completion",
  1901. "data": {
  1902. "usage": usage,
  1903. },
  1904. }
  1905. )
  1906. if not choices:
  1907. error = data.get("error", {})
  1908. if error:
  1909. await event_emitter(
  1910. {
  1911. "type": "chat:completion",
  1912. "data": {
  1913. "error": error,
  1914. },
  1915. }
  1916. )
  1917. continue
  1918. delta = choices[0].get("delta", {})
  1919. delta_tool_calls = delta.get("tool_calls", None)
  1920. if delta_tool_calls:
  1921. for delta_tool_call in delta_tool_calls:
  1922. tool_call_index = delta_tool_call.get(
  1923. "index"
  1924. )
  1925. if tool_call_index is not None:
  1926. # Check if the tool call already exists
  1927. current_response_tool_call = None
  1928. for (
  1929. response_tool_call
  1930. ) in response_tool_calls:
  1931. if (
  1932. response_tool_call.get("index")
  1933. == tool_call_index
  1934. ):
  1935. current_response_tool_call = (
  1936. response_tool_call
  1937. )
  1938. break
  1939. if current_response_tool_call is None:
  1940. # Add the new tool call
  1941. delta_tool_call.setdefault(
  1942. "function", {}
  1943. )
  1944. delta_tool_call[
  1945. "function"
  1946. ].setdefault("name", "")
  1947. delta_tool_call[
  1948. "function"
  1949. ].setdefault("arguments", "")
  1950. response_tool_calls.append(
  1951. delta_tool_call
  1952. )
  1953. else:
  1954. # Update the existing tool call
  1955. delta_name = delta_tool_call.get(
  1956. "function", {}
  1957. ).get("name")
  1958. delta_arguments = (
  1959. delta_tool_call.get(
  1960. "function", {}
  1961. ).get("arguments")
  1962. )
  1963. if delta_name:
  1964. current_response_tool_call[
  1965. "function"
  1966. ]["name"] += delta_name
  1967. if delta_arguments:
  1968. current_response_tool_call[
  1969. "function"
  1970. ][
  1971. "arguments"
  1972. ] += delta_arguments
  1973. value = delta.get("content")
  1974. reasoning_content = (
  1975. delta.get("reasoning_content")
  1976. or delta.get("reasoning")
  1977. or delta.get("thinking")
  1978. )
  1979. if reasoning_content:
  1980. if (
  1981. not content_blocks
  1982. or content_blocks[-1]["type"] != "reasoning"
  1983. ):
  1984. reasoning_block = {
  1985. "type": "reasoning",
  1986. "start_tag": "<think>",
  1987. "end_tag": "</think>",
  1988. "attributes": {
  1989. "type": "reasoning_content"
  1990. },
  1991. "content": "",
  1992. "started_at": time.time(),
  1993. }
  1994. content_blocks.append(reasoning_block)
  1995. else:
  1996. reasoning_block = content_blocks[-1]
  1997. reasoning_block["content"] += reasoning_content
  1998. data = {
  1999. "content": serialize_content_blocks(
  2000. content_blocks
  2001. )
  2002. }
  2003. if value:
  2004. if (
  2005. content_blocks
  2006. and content_blocks[-1]["type"]
  2007. == "reasoning"
  2008. and content_blocks[-1]
  2009. .get("attributes", {})
  2010. .get("type")
  2011. == "reasoning_content"
  2012. ):
  2013. reasoning_block = content_blocks[-1]
  2014. reasoning_block["ended_at"] = time.time()
  2015. reasoning_block["duration"] = int(
  2016. reasoning_block["ended_at"]
  2017. - reasoning_block["started_at"]
  2018. )
  2019. content_blocks.append(
  2020. {
  2021. "type": "text",
  2022. "content": "",
  2023. }
  2024. )
  2025. content = f"{content}{value}"
  2026. if not content_blocks:
  2027. content_blocks.append(
  2028. {
  2029. "type": "text",
  2030. "content": "",
  2031. }
  2032. )
  2033. content_blocks[-1]["content"] = (
  2034. content_blocks[-1]["content"] + value
  2035. )
  2036. if DETECT_REASONING_TAGS:
  2037. content, content_blocks, _ = (
  2038. tag_content_handler(
  2039. "reasoning",
  2040. reasoning_tags,
  2041. content,
  2042. content_blocks,
  2043. )
  2044. )
  2045. content, content_blocks, _ = (
  2046. tag_content_handler(
  2047. "solution",
  2048. DEFAULT_SOLUTION_TAGS,
  2049. content,
  2050. content_blocks,
  2051. )
  2052. )
  2053. if DETECT_CODE_INTERPRETER:
  2054. content, content_blocks, end = (
  2055. tag_content_handler(
  2056. "code_interpreter",
  2057. DEFAULT_CODE_INTERPRETER_TAGS,
  2058. content,
  2059. content_blocks,
  2060. )
  2061. )
  2062. if end:
  2063. break
  2064. if ENABLE_REALTIME_CHAT_SAVE:
  2065. # Save message in the database
  2066. Chats.upsert_message_to_chat_by_id_and_message_id(
  2067. metadata["chat_id"],
  2068. metadata["message_id"],
  2069. {
  2070. "content": serialize_content_blocks(
  2071. content_blocks
  2072. ),
  2073. },
  2074. )
  2075. else:
  2076. data = {
  2077. "content": serialize_content_blocks(
  2078. content_blocks
  2079. ),
  2080. }
  2081. if delta:
  2082. delta_count += 1
  2083. last_delta_data = data
  2084. if delta_count >= delta_chunk_size:
  2085. await flush_pending_delta_data(delta_chunk_size)
  2086. else:
  2087. await event_emitter(
  2088. {
  2089. "type": "chat:completion",
  2090. "data": data,
  2091. }
  2092. )
  2093. except Exception as e:
  2094. done = "data: [DONE]" in line
  2095. if done:
  2096. pass
  2097. else:
  2098. log.debug(f"Error: {e}")
  2099. continue
  2100. await flush_pending_delta_data()
  2101. if content_blocks:
  2102. # Clean up the last text block
  2103. if content_blocks[-1]["type"] == "text":
  2104. content_blocks[-1]["content"] = content_blocks[-1][
  2105. "content"
  2106. ].strip()
  2107. if not content_blocks[-1]["content"]:
  2108. content_blocks.pop()
  2109. if not content_blocks:
  2110. content_blocks.append(
  2111. {
  2112. "type": "text",
  2113. "content": "",
  2114. }
  2115. )
  2116. if content_blocks[-1]["type"] == "reasoning":
  2117. reasoning_block = content_blocks[-1]
  2118. if reasoning_block.get("ended_at") is None:
  2119. reasoning_block["ended_at"] = time.time()
  2120. reasoning_block["duration"] = int(
  2121. reasoning_block["ended_at"]
  2122. - reasoning_block["started_at"]
  2123. )
  2124. if response_tool_calls:
  2125. tool_calls.append(response_tool_calls)
  2126. if response.background:
  2127. await response.background()
  2128. await stream_body_handler(response, form_data)
  2129. tool_call_retries = 0
  2130. while (
  2131. len(tool_calls) > 0
  2132. and tool_call_retries < CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES
  2133. ):
  2134. tool_call_retries += 1
  2135. response_tool_calls = tool_calls.pop(0)
  2136. content_blocks.append(
  2137. {
  2138. "type": "tool_calls",
  2139. "content": response_tool_calls,
  2140. }
  2141. )
  2142. await event_emitter(
  2143. {
  2144. "type": "chat:completion",
  2145. "data": {
  2146. "content": serialize_content_blocks(content_blocks),
  2147. },
  2148. }
  2149. )
  2150. tools = metadata.get("tools", {})
  2151. results = []
  2152. for tool_call in response_tool_calls:
  2153. print("tool_call", tool_call)
  2154. tool_call_id = tool_call.get("id", "")
  2155. tool_name = tool_call.get("function", {}).get("name", "")
  2156. tool_args = tool_call.get("function", {}).get("arguments", "{}")
  2157. tool_function_params = {}
  2158. try:
  2159. # json.loads cannot be used because some models do not produce valid JSON
  2160. tool_function_params = ast.literal_eval(tool_args)
  2161. except Exception as e:
  2162. log.debug(e)
  2163. # Fallback to JSON parsing
  2164. try:
  2165. tool_function_params = json.loads(tool_args)
  2166. except Exception as e:
  2167. log.error(
  2168. f"Error parsing tool call arguments: {tool_args}"
  2169. )
  2170. # Mutate the original tool call response params as they are passed back to the passed
  2171. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  2172. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  2173. # params are not valid json.
  2174. # Main case so far is no args = "" = invalid json.
  2175. log.debug(
  2176. f"Parsed args from {tool_args} to {tool_function_params}"
  2177. )
  2178. tool_call.setdefault("function", {})["arguments"] = json.dumps(
  2179. tool_function_params
  2180. )
  2181. tool_result = None
  2182. if tool_name in tools:
  2183. tool = tools[tool_name]
  2184. spec = tool.get("spec", {})
  2185. try:
  2186. allowed_params = (
  2187. spec.get("parameters", {})
  2188. .get("properties", {})
  2189. .keys()
  2190. )
  2191. tool_function_params = {
  2192. k: v
  2193. for k, v in tool_function_params.items()
  2194. if k in allowed_params
  2195. }
  2196. if tool.get("direct", False):
  2197. tool_result = await event_caller(
  2198. {
  2199. "type": "execute:tool",
  2200. "data": {
  2201. "id": str(uuid4()),
  2202. "name": tool_name,
  2203. "params": tool_function_params,
  2204. "server": tool.get("server", {}),
  2205. "session_id": metadata.get(
  2206. "session_id", None
  2207. ),
  2208. },
  2209. }
  2210. )
  2211. else:
  2212. tool_function = tool["callable"]
  2213. tool_result = await tool_function(
  2214. **tool_function_params
  2215. )
  2216. except Exception as e:
  2217. tool_result = str(e)
  2218. tool_result_embeds = []
  2219. if isinstance(tool_result, HTMLResponse):
  2220. content_disposition = tool_result.headers.get(
  2221. "Content-Disposition", ""
  2222. )
  2223. if "inline" in content_disposition:
  2224. content = tool_result.body.decode("utf-8")
  2225. tool_result_embeds.append(content)
  2226. if 200 <= tool_result.status_code < 300:
  2227. tool_result = {
  2228. "status": "success",
  2229. "code": "ui_component",
  2230. "message": "Embedded UI result is active and visible to the user.",
  2231. }
  2232. elif 400 <= tool_result.status_code < 500:
  2233. tool_result = {
  2234. "status": "error",
  2235. "code": "ui_component",
  2236. "message": f"Client error {tool_result.status_code} from embedded UI result.",
  2237. }
  2238. elif 500 <= tool_result.status_code < 600:
  2239. tool_result = {
  2240. "status": "error",
  2241. "code": "ui_component",
  2242. "message": f"Server error {tool_result.status_code} from embedded UI result.",
  2243. }
  2244. else:
  2245. tool_result = {
  2246. "status": "error",
  2247. "code": "ui_component",
  2248. "message": f"Unexpected status code {tool_result.status_code} from embedded UI result.",
  2249. }
  2250. else:
  2251. tool_result = tool_result.body.decode("utf-8")
  2252. elif (
  2253. tool.get("type") == "external"
  2254. and isinstance(tool_result, tuple)
  2255. ) or (
  2256. tool.get("direct", True)
  2257. and isinstance(tool_result, list)
  2258. and len(tool_result) == 2
  2259. ):
  2260. tool_result, tool_response_headers = tool_result
  2261. try:
  2262. if not isinstance(tool_response_headers, dict):
  2263. tool_response_headers = dict(tool_response_headers)
  2264. except Exception as e:
  2265. tool_response_headers = {}
  2266. log.debug(e)
  2267. print(tool_response_headers)
  2268. print(type(tool_response_headers))
  2269. if tool_response_headers and isinstance(
  2270. tool_response_headers, dict
  2271. ):
  2272. content_disposition = tool_response_headers.get(
  2273. "Content-Disposition",
  2274. tool_response_headers.get(
  2275. "content-disposition", ""
  2276. ),
  2277. )
  2278. if "inline" in content_disposition:
  2279. content_type = tool_response_headers.get(
  2280. "Content-Type",
  2281. tool_response_headers.get("content-type", ""),
  2282. )
  2283. location = tool_response_headers.get(
  2284. "Location",
  2285. tool_response_headers.get("location", ""),
  2286. )
  2287. if "text/html" in content_type:
  2288. # Display as iframe embed
  2289. tool_result_embeds.append(tool_result)
  2290. tool_result = {
  2291. "status": "success",
  2292. "code": "ui_component",
  2293. "message": "Embedded UI result is active and visible to the user.",
  2294. }
  2295. elif location:
  2296. tool_result_embeds.append(location)
  2297. tool_result = {
  2298. "status": "success",
  2299. "code": "ui_component",
  2300. "message": "Embedded UI result is active and visible to the user.",
  2301. }
  2302. tool_result_files = []
  2303. if isinstance(tool_result, list):
  2304. if tool.get("type") == "mcp": # MCP
  2305. tool_response = []
  2306. for item in tool_result:
  2307. if isinstance(item, dict):
  2308. if item.get("type") == "text":
  2309. text = item.get("text", "")
  2310. if isinstance(text, str):
  2311. try:
  2312. text = json.loads(text)
  2313. except json.JSONDecodeError:
  2314. pass
  2315. tool_response.append(text)
  2316. elif item.get("type") in ["image", "audio"]:
  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 = (
  2341. tool_response[0]
  2342. if len(tool_response) == 1
  2343. else tool_response
  2344. )
  2345. else: # OpenAPI
  2346. for item in tool_result:
  2347. # check if string
  2348. if isinstance(item, str) and item.startswith(
  2349. "data:"
  2350. ):
  2351. tool_result_files.append(
  2352. {
  2353. "type": "data",
  2354. "content": item,
  2355. }
  2356. )
  2357. tool_result.remove(item)
  2358. if tool_result_files:
  2359. if not isinstance(tool_result, list):
  2360. tool_result = [
  2361. tool_result,
  2362. ]
  2363. for file in tool_result_files:
  2364. tool_result.append(
  2365. {
  2366. "type": file.get("type", "data"),
  2367. "content": "Result is being displayed as a file.",
  2368. }
  2369. )
  2370. if isinstance(tool_result, dict) or isinstance(
  2371. tool_result, list
  2372. ):
  2373. tool_result = json.dumps(
  2374. tool_result, indent=2, ensure_ascii=False
  2375. )
  2376. results.append(
  2377. {
  2378. "tool_call_id": tool_call_id,
  2379. "content": tool_result or "",
  2380. **(
  2381. {"files": tool_result_files}
  2382. if tool_result_files
  2383. else {}
  2384. ),
  2385. **(
  2386. {"embeds": tool_result_embeds}
  2387. if tool_result_embeds
  2388. else {}
  2389. ),
  2390. }
  2391. )
  2392. content_blocks[-1]["results"] = results
  2393. content_blocks.append(
  2394. {
  2395. "type": "text",
  2396. "content": "",
  2397. }
  2398. )
  2399. await event_emitter(
  2400. {
  2401. "type": "chat:completion",
  2402. "data": {
  2403. "content": serialize_content_blocks(content_blocks),
  2404. },
  2405. }
  2406. )
  2407. try:
  2408. new_form_data = {
  2409. "model": model_id,
  2410. "stream": True,
  2411. "tools": form_data["tools"],
  2412. "messages": [
  2413. *form_data["messages"],
  2414. *convert_content_blocks_to_messages(
  2415. content_blocks, True
  2416. ),
  2417. ],
  2418. }
  2419. res = await generate_chat_completion(
  2420. request,
  2421. new_form_data,
  2422. user,
  2423. )
  2424. if isinstance(res, StreamingResponse):
  2425. await stream_body_handler(res, new_form_data)
  2426. else:
  2427. break
  2428. except Exception as e:
  2429. log.debug(e)
  2430. break
  2431. if DETECT_CODE_INTERPRETER:
  2432. MAX_RETRIES = 5
  2433. retries = 0
  2434. while (
  2435. content_blocks[-1]["type"] == "code_interpreter"
  2436. and retries < MAX_RETRIES
  2437. ):
  2438. await event_emitter(
  2439. {
  2440. "type": "chat:completion",
  2441. "data": {
  2442. "content": serialize_content_blocks(content_blocks),
  2443. },
  2444. }
  2445. )
  2446. retries += 1
  2447. log.debug(f"Attempt count: {retries}")
  2448. output = ""
  2449. try:
  2450. if content_blocks[-1]["attributes"].get("type") == "code":
  2451. code = content_blocks[-1]["content"]
  2452. if CODE_INTERPRETER_BLOCKED_MODULES:
  2453. blocking_code = textwrap.dedent(
  2454. f"""
  2455. import builtins
  2456. BLOCKED_MODULES = {CODE_INTERPRETER_BLOCKED_MODULES}
  2457. _real_import = builtins.__import__
  2458. def restricted_import(name, globals=None, locals=None, fromlist=(), level=0):
  2459. if name.split('.')[0] in BLOCKED_MODULES:
  2460. importer_name = globals.get('__name__') if globals else None
  2461. if importer_name == '__main__':
  2462. raise ImportError(
  2463. f"Direct import of module {{name}} is restricted."
  2464. )
  2465. return _real_import(name, globals, locals, fromlist, level)
  2466. builtins.__import__ = restricted_import
  2467. """
  2468. )
  2469. code = blocking_code + "\n" + code
  2470. if (
  2471. request.app.state.config.CODE_INTERPRETER_ENGINE
  2472. == "pyodide"
  2473. ):
  2474. output = await event_caller(
  2475. {
  2476. "type": "execute:python",
  2477. "data": {
  2478. "id": str(uuid4()),
  2479. "code": code,
  2480. "session_id": metadata.get(
  2481. "session_id", None
  2482. ),
  2483. },
  2484. }
  2485. )
  2486. elif (
  2487. request.app.state.config.CODE_INTERPRETER_ENGINE
  2488. == "jupyter"
  2489. ):
  2490. output = await execute_code_jupyter(
  2491. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  2492. code,
  2493. (
  2494. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  2495. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2496. == "token"
  2497. else None
  2498. ),
  2499. (
  2500. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  2501. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2502. == "password"
  2503. else None
  2504. ),
  2505. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  2506. )
  2507. else:
  2508. output = {
  2509. "stdout": "Code interpreter engine not configured."
  2510. }
  2511. log.debug(f"Code interpreter output: {output}")
  2512. if isinstance(output, dict):
  2513. stdout = output.get("stdout", "")
  2514. if isinstance(stdout, str):
  2515. stdoutLines = stdout.split("\n")
  2516. for idx, line in enumerate(stdoutLines):
  2517. if "data:image/png;base64" in line:
  2518. image_url = get_image_url_from_base64(
  2519. request,
  2520. line,
  2521. metadata,
  2522. user,
  2523. )
  2524. if image_url:
  2525. stdoutLines[idx] = (
  2526. f"![Output Image]({image_url})"
  2527. )
  2528. output["stdout"] = "\n".join(stdoutLines)
  2529. result = output.get("result", "")
  2530. if isinstance(result, str):
  2531. resultLines = result.split("\n")
  2532. for idx, line in enumerate(resultLines):
  2533. if "data:image/png;base64" in line:
  2534. image_url = get_image_url_from_base64(
  2535. request,
  2536. line,
  2537. metadata,
  2538. user,
  2539. )
  2540. resultLines[idx] = (
  2541. f"![Output Image]({image_url})"
  2542. )
  2543. output["result"] = "\n".join(resultLines)
  2544. except Exception as e:
  2545. output = str(e)
  2546. content_blocks[-1]["output"] = output
  2547. content_blocks.append(
  2548. {
  2549. "type": "text",
  2550. "content": "",
  2551. }
  2552. )
  2553. await event_emitter(
  2554. {
  2555. "type": "chat:completion",
  2556. "data": {
  2557. "content": serialize_content_blocks(content_blocks),
  2558. },
  2559. }
  2560. )
  2561. try:
  2562. new_form_data = {
  2563. "model": model_id,
  2564. "stream": True,
  2565. "messages": [
  2566. *form_data["messages"],
  2567. {
  2568. "role": "assistant",
  2569. "content": serialize_content_blocks(
  2570. content_blocks, raw=True
  2571. ),
  2572. },
  2573. ],
  2574. }
  2575. res = await generate_chat_completion(
  2576. request,
  2577. new_form_data,
  2578. user,
  2579. )
  2580. if isinstance(res, StreamingResponse):
  2581. await stream_body_handler(res, new_form_data)
  2582. else:
  2583. break
  2584. except Exception as e:
  2585. log.debug(e)
  2586. break
  2587. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  2588. data = {
  2589. "done": True,
  2590. "content": serialize_content_blocks(content_blocks),
  2591. "title": title,
  2592. }
  2593. if not ENABLE_REALTIME_CHAT_SAVE:
  2594. # Save message in the database
  2595. Chats.upsert_message_to_chat_by_id_and_message_id(
  2596. metadata["chat_id"],
  2597. metadata["message_id"],
  2598. {
  2599. "content": serialize_content_blocks(content_blocks),
  2600. },
  2601. )
  2602. # Send a webhook notification if the user is not active
  2603. if not get_active_status_by_user_id(user.id):
  2604. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  2605. if webhook_url:
  2606. await post_webhook(
  2607. request.app.state.WEBUI_NAME,
  2608. webhook_url,
  2609. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  2610. {
  2611. "action": "chat",
  2612. "message": content,
  2613. "title": title,
  2614. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  2615. },
  2616. )
  2617. await event_emitter(
  2618. {
  2619. "type": "chat:completion",
  2620. "data": data,
  2621. }
  2622. )
  2623. await background_tasks_handler()
  2624. except asyncio.CancelledError:
  2625. log.warning("Task was cancelled!")
  2626. await event_emitter({"type": "chat:tasks:cancel"})
  2627. if not ENABLE_REALTIME_CHAT_SAVE:
  2628. # Save message in the database
  2629. Chats.upsert_message_to_chat_by_id_and_message_id(
  2630. metadata["chat_id"],
  2631. metadata["message_id"],
  2632. {
  2633. "content": serialize_content_blocks(content_blocks),
  2634. },
  2635. )
  2636. if response.background is not None:
  2637. await response.background()
  2638. return await response_handler(response, events)
  2639. else:
  2640. # Fallback to the original response
  2641. async def stream_wrapper(original_generator, events):
  2642. def wrap_item(item):
  2643. return f"data: {item}\n\n"
  2644. for event in events:
  2645. event, _ = await process_filter_functions(
  2646. request=request,
  2647. filter_functions=filter_functions,
  2648. filter_type="stream",
  2649. form_data=event,
  2650. extra_params=extra_params,
  2651. )
  2652. if event:
  2653. yield wrap_item(json.dumps(event))
  2654. async for data in original_generator:
  2655. data, _ = await process_filter_functions(
  2656. request=request,
  2657. filter_functions=filter_functions,
  2658. filter_type="stream",
  2659. form_data=data,
  2660. extra_params=extra_params,
  2661. )
  2662. if data:
  2663. yield data
  2664. return StreamingResponse(
  2665. stream_wrapper(response.body_iterator, events),
  2666. headers=dict(response.headers),
  2667. background=response.background,
  2668. )