middleware.py 123 KB

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