1
0

middleware.py 124 KB

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