middleware.py 125 KB

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