middleware.py 129 KB

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