middleware.py 124 KB

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