1
0

middleware.py 128 KB

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