middleware.py 128 KB

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