middleware.py 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204
  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. if tasks[TASKS.TITLE_GENERATION]:
  1412. res = await generate_title(
  1413. request,
  1414. {
  1415. "model": message["model"],
  1416. "messages": messages,
  1417. "chat_id": metadata["chat_id"],
  1418. },
  1419. user,
  1420. )
  1421. if res and isinstance(res, dict):
  1422. if len(res.get("choices", [])) == 1:
  1423. response_message = res.get("choices", [])[0].get(
  1424. "message", {}
  1425. )
  1426. title_string = (
  1427. response_message.get("content")
  1428. or response_message.get(
  1429. "reasoning_content",
  1430. )
  1431. or message.get("content", user_message)
  1432. )
  1433. else:
  1434. title_string = ""
  1435. title_string = title_string[
  1436. title_string.find("{") : title_string.rfind("}") + 1
  1437. ]
  1438. try:
  1439. title = json.loads(title_string).get(
  1440. "title", user_message
  1441. )
  1442. except Exception as e:
  1443. title = ""
  1444. if not title:
  1445. title = messages[0].get("content", user_message)
  1446. Chats.update_chat_title_by_id(
  1447. metadata["chat_id"], title
  1448. )
  1449. await event_emitter(
  1450. {
  1451. "type": "chat:title",
  1452. "data": title,
  1453. }
  1454. )
  1455. elif len(messages) == 2:
  1456. title = messages[0].get("content", user_message)
  1457. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1458. await event_emitter(
  1459. {
  1460. "type": "chat:title",
  1461. "data": message.get("content", user_message),
  1462. }
  1463. )
  1464. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  1465. res = await generate_chat_tags(
  1466. request,
  1467. {
  1468. "model": message["model"],
  1469. "messages": messages,
  1470. "chat_id": metadata["chat_id"],
  1471. },
  1472. user,
  1473. )
  1474. if res and isinstance(res, dict):
  1475. if len(res.get("choices", [])) == 1:
  1476. response_message = res.get("choices", [])[0].get(
  1477. "message", {}
  1478. )
  1479. tags_string = response_message.get(
  1480. "content"
  1481. ) or response_message.get("reasoning_content", "")
  1482. else:
  1483. tags_string = ""
  1484. tags_string = tags_string[
  1485. tags_string.find("{") : tags_string.rfind("}") + 1
  1486. ]
  1487. try:
  1488. tags = json.loads(tags_string).get("tags", [])
  1489. Chats.update_chat_tags_by_id(
  1490. metadata["chat_id"], tags, user
  1491. )
  1492. await event_emitter(
  1493. {
  1494. "type": "chat:tags",
  1495. "data": tags,
  1496. }
  1497. )
  1498. except Exception as e:
  1499. pass
  1500. event_emitter = None
  1501. event_caller = None
  1502. if (
  1503. "session_id" in metadata
  1504. and metadata["session_id"]
  1505. and "chat_id" in metadata
  1506. and metadata["chat_id"]
  1507. and "message_id" in metadata
  1508. and metadata["message_id"]
  1509. ):
  1510. event_emitter = get_event_emitter(metadata)
  1511. event_caller = get_event_call(metadata)
  1512. # Non-streaming response
  1513. if not isinstance(response, StreamingResponse):
  1514. if event_emitter:
  1515. try:
  1516. if isinstance(response, dict) or isinstance(response, JSONResponse):
  1517. if isinstance(response, list) and len(response) == 1:
  1518. # If the response is a single-item list, unwrap it #17213
  1519. response = response[0]
  1520. if isinstance(response, JSONResponse) and isinstance(
  1521. response.body, bytes
  1522. ):
  1523. try:
  1524. response_data = json.loads(
  1525. response.body.decode("utf-8", "replace")
  1526. )
  1527. except json.JSONDecodeError:
  1528. response_data = {
  1529. "error": {"detail": "Invalid JSON response"}
  1530. }
  1531. else:
  1532. response_data = response
  1533. if "error" in response_data:
  1534. error = response_data.get("error")
  1535. if isinstance(error, dict):
  1536. error = error.get("detail", error)
  1537. else:
  1538. error = str(error)
  1539. Chats.upsert_message_to_chat_by_id_and_message_id(
  1540. metadata["chat_id"],
  1541. metadata["message_id"],
  1542. {
  1543. "error": {"content": error},
  1544. },
  1545. )
  1546. if isinstance(error, str) or isinstance(error, dict):
  1547. await event_emitter(
  1548. {
  1549. "type": "chat:message:error",
  1550. "data": {"error": {"content": error}},
  1551. }
  1552. )
  1553. if "selected_model_id" in response_data:
  1554. Chats.upsert_message_to_chat_by_id_and_message_id(
  1555. metadata["chat_id"],
  1556. metadata["message_id"],
  1557. {
  1558. "selectedModelId": response_data["selected_model_id"],
  1559. },
  1560. )
  1561. choices = response_data.get("choices", [])
  1562. if choices and choices[0].get("message", {}).get("content"):
  1563. content = response_data["choices"][0]["message"]["content"]
  1564. if content:
  1565. await event_emitter(
  1566. {
  1567. "type": "chat:completion",
  1568. "data": response_data,
  1569. }
  1570. )
  1571. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1572. await event_emitter(
  1573. {
  1574. "type": "chat:completion",
  1575. "data": {
  1576. "done": True,
  1577. "content": content,
  1578. "title": title,
  1579. },
  1580. }
  1581. )
  1582. # Save message in the database
  1583. Chats.upsert_message_to_chat_by_id_and_message_id(
  1584. metadata["chat_id"],
  1585. metadata["message_id"],
  1586. {
  1587. "role": "assistant",
  1588. "content": content,
  1589. },
  1590. )
  1591. # Send a webhook notification if the user is not active
  1592. if not get_active_status_by_user_id(user.id):
  1593. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1594. if webhook_url:
  1595. await post_webhook(
  1596. request.app.state.WEBUI_NAME,
  1597. webhook_url,
  1598. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1599. {
  1600. "action": "chat",
  1601. "message": content,
  1602. "title": title,
  1603. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1604. },
  1605. )
  1606. await background_tasks_handler()
  1607. if events and isinstance(events, list):
  1608. extra_response = {}
  1609. for event in events:
  1610. if isinstance(event, dict):
  1611. extra_response.update(event)
  1612. else:
  1613. extra_response[event] = True
  1614. response_data = {
  1615. **extra_response,
  1616. **response_data,
  1617. }
  1618. if isinstance(response, dict):
  1619. response = response_data
  1620. if isinstance(response, JSONResponse):
  1621. response = JSONResponse(
  1622. content=response_data,
  1623. headers=response.headers,
  1624. status_code=response.status_code,
  1625. )
  1626. except Exception as e:
  1627. log.debug(f"Error occurred while processing request: {e}")
  1628. pass
  1629. return response
  1630. else:
  1631. if events and isinstance(events, list) and isinstance(response, dict):
  1632. extra_response = {}
  1633. for event in events:
  1634. if isinstance(event, dict):
  1635. extra_response.update(event)
  1636. else:
  1637. extra_response[event] = True
  1638. response = {
  1639. **extra_response,
  1640. **response,
  1641. }
  1642. return response
  1643. # Non standard response
  1644. if not any(
  1645. content_type in response.headers["Content-Type"]
  1646. for content_type in ["text/event-stream", "application/x-ndjson"]
  1647. ):
  1648. return response
  1649. oauth_token = None
  1650. try:
  1651. if request.cookies.get("oauth_session_id", None):
  1652. oauth_token = await request.app.state.oauth_manager.get_oauth_token(
  1653. user.id,
  1654. request.cookies.get("oauth_session_id", None),
  1655. )
  1656. except Exception as e:
  1657. log.error(f"Error getting OAuth token: {e}")
  1658. extra_params = {
  1659. "__event_emitter__": event_emitter,
  1660. "__event_call__": event_caller,
  1661. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  1662. "__metadata__": metadata,
  1663. "__oauth_token__": oauth_token,
  1664. "__request__": request,
  1665. "__model__": model,
  1666. }
  1667. filter_functions = [
  1668. Functions.get_function_by_id(filter_id)
  1669. for filter_id in get_sorted_filter_ids(
  1670. request, model, metadata.get("filter_ids", [])
  1671. )
  1672. ]
  1673. # Streaming response
  1674. if event_emitter and event_caller:
  1675. task_id = str(uuid4()) # Create a unique task ID.
  1676. model_id = form_data.get("model", "")
  1677. def split_content_and_whitespace(content):
  1678. content_stripped = content.rstrip()
  1679. original_whitespace = (
  1680. content[len(content_stripped) :]
  1681. if len(content) > len(content_stripped)
  1682. else ""
  1683. )
  1684. return content_stripped, original_whitespace
  1685. def is_opening_code_block(content):
  1686. backtick_segments = content.split("```")
  1687. # Even number of segments means the last backticks are opening a new block
  1688. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  1689. # Handle as a background task
  1690. async def response_handler(response, events):
  1691. def serialize_content_blocks(content_blocks, raw=False):
  1692. content = ""
  1693. for block in content_blocks:
  1694. if block["type"] == "text":
  1695. block_content = block["content"].strip()
  1696. if block_content:
  1697. content = f"{content}{block_content}\n"
  1698. elif block["type"] == "tool_calls":
  1699. attributes = block.get("attributes", {})
  1700. tool_calls = block.get("content", [])
  1701. results = block.get("results", [])
  1702. if content and not content.endswith("\n"):
  1703. content += "\n"
  1704. if results:
  1705. tool_calls_display_content = ""
  1706. for tool_call in tool_calls:
  1707. tool_call_id = tool_call.get("id", "")
  1708. tool_name = tool_call.get("function", {}).get(
  1709. "name", ""
  1710. )
  1711. tool_arguments = tool_call.get("function", {}).get(
  1712. "arguments", ""
  1713. )
  1714. tool_result = None
  1715. tool_result_files = None
  1716. for result in results:
  1717. if tool_call_id == result.get("tool_call_id", ""):
  1718. tool_result = result.get("content", None)
  1719. tool_result_files = result.get("files", None)
  1720. break
  1721. if tool_result is not None:
  1722. tool_result_embeds = result.get("embeds", "")
  1723. 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'
  1724. else:
  1725. 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'
  1726. if not raw:
  1727. content = f"{content}{tool_calls_display_content}"
  1728. else:
  1729. tool_calls_display_content = ""
  1730. for tool_call in tool_calls:
  1731. tool_call_id = tool_call.get("id", "")
  1732. tool_name = tool_call.get("function", {}).get(
  1733. "name", ""
  1734. )
  1735. tool_arguments = tool_call.get("function", {}).get(
  1736. "arguments", ""
  1737. )
  1738. 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'
  1739. if not raw:
  1740. content = f"{content}{tool_calls_display_content}"
  1741. elif block["type"] == "reasoning":
  1742. reasoning_display_content = html.escape(
  1743. "\n".join(
  1744. (f"> {line}" if not line.startswith(">") else line)
  1745. for line in block["content"].splitlines()
  1746. )
  1747. )
  1748. reasoning_duration = block.get("duration", None)
  1749. start_tag = block.get("start_tag", "")
  1750. end_tag = block.get("end_tag", "")
  1751. if content and not content.endswith("\n"):
  1752. content += "\n"
  1753. if reasoning_duration is not None:
  1754. if raw:
  1755. content = (
  1756. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1757. )
  1758. else:
  1759. 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'
  1760. else:
  1761. if raw:
  1762. content = (
  1763. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1764. )
  1765. else:
  1766. content = f'{content}<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1767. elif block["type"] == "code_interpreter":
  1768. attributes = block.get("attributes", {})
  1769. output = block.get("output", None)
  1770. lang = attributes.get("lang", "")
  1771. content_stripped, original_whitespace = (
  1772. split_content_and_whitespace(content)
  1773. )
  1774. if is_opening_code_block(content_stripped):
  1775. # Remove trailing backticks that would open a new block
  1776. content = (
  1777. content_stripped.rstrip("`").rstrip()
  1778. + original_whitespace
  1779. )
  1780. else:
  1781. # Keep content as is - either closing backticks or no backticks
  1782. content = content_stripped + original_whitespace
  1783. if content and not content.endswith("\n"):
  1784. content += "\n"
  1785. if output:
  1786. output = html.escape(json.dumps(output))
  1787. if raw:
  1788. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1789. else:
  1790. content = f'{content}<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1791. else:
  1792. if raw:
  1793. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1794. else:
  1795. content = f'{content}<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1796. else:
  1797. block_content = str(block["content"]).strip()
  1798. if block_content:
  1799. content = f"{content}{block['type']}: {block_content}\n"
  1800. return content.strip()
  1801. def convert_content_blocks_to_messages(content_blocks, raw=False):
  1802. messages = []
  1803. temp_blocks = []
  1804. for idx, block in enumerate(content_blocks):
  1805. if block["type"] == "tool_calls":
  1806. messages.append(
  1807. {
  1808. "role": "assistant",
  1809. "content": serialize_content_blocks(temp_blocks, raw),
  1810. "tool_calls": block.get("content"),
  1811. }
  1812. )
  1813. results = block.get("results", [])
  1814. for result in results:
  1815. messages.append(
  1816. {
  1817. "role": "tool",
  1818. "tool_call_id": result["tool_call_id"],
  1819. "content": result.get("content", "") or "",
  1820. }
  1821. )
  1822. temp_blocks = []
  1823. else:
  1824. temp_blocks.append(block)
  1825. if temp_blocks:
  1826. content = serialize_content_blocks(temp_blocks, raw)
  1827. if content:
  1828. messages.append(
  1829. {
  1830. "role": "assistant",
  1831. "content": content,
  1832. }
  1833. )
  1834. return messages
  1835. def tag_content_handler(content_type, tags, content, content_blocks):
  1836. end_flag = False
  1837. def extract_attributes(tag_content):
  1838. """Extract attributes from a tag if they exist."""
  1839. attributes = {}
  1840. if not tag_content: # Ensure tag_content is not None
  1841. return attributes
  1842. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1843. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1844. for key, value in matches:
  1845. attributes[key] = value
  1846. return attributes
  1847. if content_blocks[-1]["type"] == "text":
  1848. for start_tag, end_tag in tags:
  1849. start_tag_pattern = rf"{re.escape(start_tag)}"
  1850. if start_tag.startswith("<") and start_tag.endswith(">"):
  1851. # Match start tag e.g., <tag> or <tag attr="value">
  1852. # remove both '<' and '>' from start_tag
  1853. # Match start tag with attributes
  1854. start_tag_pattern = (
  1855. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1856. )
  1857. match = re.search(start_tag_pattern, content)
  1858. if match:
  1859. try:
  1860. attr_content = (
  1861. match.group(1) if match.group(1) else ""
  1862. ) # Ensure it's not None
  1863. except:
  1864. attr_content = ""
  1865. attributes = extract_attributes(
  1866. attr_content
  1867. ) # Extract attributes safely
  1868. # Capture everything before and after the matched tag
  1869. before_tag = content[
  1870. : match.start()
  1871. ] # Content before opening tag
  1872. after_tag = content[
  1873. match.end() :
  1874. ] # Content after opening tag
  1875. # Remove the start tag and after from the currently handling text block
  1876. content_blocks[-1]["content"] = content_blocks[-1][
  1877. "content"
  1878. ].replace(match.group(0) + after_tag, "")
  1879. if before_tag:
  1880. content_blocks[-1]["content"] = before_tag
  1881. if not content_blocks[-1]["content"]:
  1882. content_blocks.pop()
  1883. # Append the new block
  1884. content_blocks.append(
  1885. {
  1886. "type": content_type,
  1887. "start_tag": start_tag,
  1888. "end_tag": end_tag,
  1889. "attributes": attributes,
  1890. "content": "",
  1891. "started_at": time.time(),
  1892. }
  1893. )
  1894. if after_tag:
  1895. content_blocks[-1]["content"] = after_tag
  1896. tag_content_handler(
  1897. content_type, tags, after_tag, content_blocks
  1898. )
  1899. break
  1900. elif content_blocks[-1]["type"] == content_type:
  1901. start_tag = content_blocks[-1]["start_tag"]
  1902. end_tag = content_blocks[-1]["end_tag"]
  1903. if end_tag.startswith("<") and end_tag.endswith(">"):
  1904. # Match end tag e.g., </tag>
  1905. end_tag_pattern = rf"{re.escape(end_tag)}"
  1906. else:
  1907. # Handle cases where end_tag is just a tag name
  1908. end_tag_pattern = rf"{re.escape(end_tag)}"
  1909. # Check if the content has the end tag
  1910. if re.search(end_tag_pattern, content):
  1911. end_flag = True
  1912. block_content = content_blocks[-1]["content"]
  1913. # Strip start and end tags from the content
  1914. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1915. block_content = re.sub(
  1916. start_tag_pattern, "", block_content
  1917. ).strip()
  1918. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1919. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1920. # Content inside the tag
  1921. block_content = (
  1922. split_content[0].strip() if split_content else ""
  1923. )
  1924. # Leftover content (everything after `</tag>`)
  1925. leftover_content = (
  1926. split_content[1].strip() if len(split_content) > 1 else ""
  1927. )
  1928. if block_content:
  1929. content_blocks[-1]["content"] = block_content
  1930. content_blocks[-1]["ended_at"] = time.time()
  1931. content_blocks[-1]["duration"] = int(
  1932. content_blocks[-1]["ended_at"]
  1933. - content_blocks[-1]["started_at"]
  1934. )
  1935. # Reset the content_blocks by appending a new text block
  1936. if content_type != "code_interpreter":
  1937. if leftover_content:
  1938. content_blocks.append(
  1939. {
  1940. "type": "text",
  1941. "content": leftover_content,
  1942. }
  1943. )
  1944. else:
  1945. content_blocks.append(
  1946. {
  1947. "type": "text",
  1948. "content": "",
  1949. }
  1950. )
  1951. else:
  1952. # Remove the block if content is empty
  1953. content_blocks.pop()
  1954. if leftover_content:
  1955. content_blocks.append(
  1956. {
  1957. "type": "text",
  1958. "content": leftover_content,
  1959. }
  1960. )
  1961. else:
  1962. content_blocks.append(
  1963. {
  1964. "type": "text",
  1965. "content": "",
  1966. }
  1967. )
  1968. # Clean processed content
  1969. start_tag_pattern = rf"{re.escape(start_tag)}"
  1970. if start_tag.startswith("<") and start_tag.endswith(">"):
  1971. # Match start tag e.g., <tag> or <tag attr="value">
  1972. # remove both '<' and '>' from start_tag
  1973. # Match start tag with attributes
  1974. start_tag_pattern = (
  1975. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1976. )
  1977. content = re.sub(
  1978. rf"{start_tag_pattern}(.|\n)*?{re.escape(end_tag)}",
  1979. "",
  1980. content,
  1981. flags=re.DOTALL,
  1982. )
  1983. return content, content_blocks, end_flag
  1984. message = Chats.get_message_by_id_and_message_id(
  1985. metadata["chat_id"], metadata["message_id"]
  1986. )
  1987. tool_calls = []
  1988. last_assistant_message = None
  1989. try:
  1990. if form_data["messages"][-1]["role"] == "assistant":
  1991. last_assistant_message = get_last_assistant_message(
  1992. form_data["messages"]
  1993. )
  1994. except Exception as e:
  1995. pass
  1996. content = (
  1997. message.get("content", "")
  1998. if message
  1999. else last_assistant_message if last_assistant_message else ""
  2000. )
  2001. content_blocks = [
  2002. {
  2003. "type": "text",
  2004. "content": content,
  2005. }
  2006. ]
  2007. reasoning_tags_param = metadata.get("params", {}).get("reasoning_tags")
  2008. DETECT_REASONING_TAGS = reasoning_tags_param is not False
  2009. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  2010. "code_interpreter", False
  2011. )
  2012. reasoning_tags = []
  2013. if DETECT_REASONING_TAGS:
  2014. if (
  2015. isinstance(reasoning_tags_param, list)
  2016. and len(reasoning_tags_param) == 2
  2017. ):
  2018. reasoning_tags = [
  2019. (reasoning_tags_param[0], reasoning_tags_param[1])
  2020. ]
  2021. else:
  2022. reasoning_tags = DEFAULT_REASONING_TAGS
  2023. try:
  2024. for event in events:
  2025. await event_emitter(
  2026. {
  2027. "type": "chat:completion",
  2028. "data": event,
  2029. }
  2030. )
  2031. # Save message in the database
  2032. Chats.upsert_message_to_chat_by_id_and_message_id(
  2033. metadata["chat_id"],
  2034. metadata["message_id"],
  2035. {
  2036. **event,
  2037. },
  2038. )
  2039. async def stream_body_handler(response, form_data):
  2040. nonlocal content
  2041. nonlocal content_blocks
  2042. response_tool_calls = []
  2043. delta_count = 0
  2044. delta_chunk_size = max(
  2045. CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
  2046. int(
  2047. metadata.get("params", {}).get("stream_delta_chunk_size")
  2048. or 1
  2049. ),
  2050. )
  2051. last_delta_data = None
  2052. async def flush_pending_delta_data(threshold: int = 0):
  2053. nonlocal delta_count
  2054. nonlocal last_delta_data
  2055. if delta_count >= threshold and last_delta_data:
  2056. await event_emitter(
  2057. {
  2058. "type": "chat:completion",
  2059. "data": last_delta_data,
  2060. }
  2061. )
  2062. delta_count = 0
  2063. last_delta_data = None
  2064. async for line in response.body_iterator:
  2065. line = (
  2066. line.decode("utf-8", "replace")
  2067. if isinstance(line, bytes)
  2068. else line
  2069. )
  2070. data = line
  2071. # Skip empty lines
  2072. if not data.strip():
  2073. continue
  2074. # "data:" is the prefix for each event
  2075. if not data.startswith("data:"):
  2076. continue
  2077. # Remove the prefix
  2078. data = data[len("data:") :].strip()
  2079. try:
  2080. data = json.loads(data)
  2081. data, _ = await process_filter_functions(
  2082. request=request,
  2083. filter_functions=filter_functions,
  2084. filter_type="stream",
  2085. form_data=data,
  2086. extra_params={"__body__": form_data, **extra_params},
  2087. )
  2088. if data:
  2089. if "event" in data and not getattr(
  2090. request.state, "direct", False
  2091. ):
  2092. await event_emitter(data.get("event", {}))
  2093. if "selected_model_id" in data:
  2094. model_id = data["selected_model_id"]
  2095. Chats.upsert_message_to_chat_by_id_and_message_id(
  2096. metadata["chat_id"],
  2097. metadata["message_id"],
  2098. {
  2099. "selectedModelId": model_id,
  2100. },
  2101. )
  2102. await event_emitter(
  2103. {
  2104. "type": "chat:completion",
  2105. "data": data,
  2106. }
  2107. )
  2108. else:
  2109. choices = data.get("choices", [])
  2110. # 17421
  2111. usage = data.get("usage", {}) or {}
  2112. usage.update(data.get("timings", {})) # llama.cpp
  2113. if usage:
  2114. await event_emitter(
  2115. {
  2116. "type": "chat:completion",
  2117. "data": {
  2118. "usage": usage,
  2119. },
  2120. }
  2121. )
  2122. if not choices:
  2123. error = data.get("error", {})
  2124. if error:
  2125. await event_emitter(
  2126. {
  2127. "type": "chat:completion",
  2128. "data": {
  2129. "error": error,
  2130. },
  2131. }
  2132. )
  2133. continue
  2134. delta = choices[0].get("delta", {})
  2135. delta_tool_calls = delta.get("tool_calls", None)
  2136. if delta_tool_calls:
  2137. for delta_tool_call in delta_tool_calls:
  2138. tool_call_index = delta_tool_call.get(
  2139. "index"
  2140. )
  2141. if tool_call_index is not None:
  2142. # Check if the tool call already exists
  2143. current_response_tool_call = None
  2144. for (
  2145. response_tool_call
  2146. ) in response_tool_calls:
  2147. if (
  2148. response_tool_call.get("index")
  2149. == tool_call_index
  2150. ):
  2151. current_response_tool_call = (
  2152. response_tool_call
  2153. )
  2154. break
  2155. if current_response_tool_call is None:
  2156. # Add the new tool call
  2157. delta_tool_call.setdefault(
  2158. "function", {}
  2159. )
  2160. delta_tool_call[
  2161. "function"
  2162. ].setdefault("name", "")
  2163. delta_tool_call[
  2164. "function"
  2165. ].setdefault("arguments", "")
  2166. response_tool_calls.append(
  2167. delta_tool_call
  2168. )
  2169. else:
  2170. # Update the existing tool call
  2171. delta_name = delta_tool_call.get(
  2172. "function", {}
  2173. ).get("name")
  2174. delta_arguments = (
  2175. delta_tool_call.get(
  2176. "function", {}
  2177. ).get("arguments")
  2178. )
  2179. if delta_name:
  2180. current_response_tool_call[
  2181. "function"
  2182. ]["name"] += delta_name
  2183. if delta_arguments:
  2184. current_response_tool_call[
  2185. "function"
  2186. ][
  2187. "arguments"
  2188. ] += delta_arguments
  2189. value = delta.get("content")
  2190. reasoning_content = (
  2191. delta.get("reasoning_content")
  2192. or delta.get("reasoning")
  2193. or delta.get("thinking")
  2194. )
  2195. if reasoning_content:
  2196. if (
  2197. not content_blocks
  2198. or content_blocks[-1]["type"] != "reasoning"
  2199. ):
  2200. reasoning_block = {
  2201. "type": "reasoning",
  2202. "start_tag": "<think>",
  2203. "end_tag": "</think>",
  2204. "attributes": {
  2205. "type": "reasoning_content"
  2206. },
  2207. "content": "",
  2208. "started_at": time.time(),
  2209. }
  2210. content_blocks.append(reasoning_block)
  2211. else:
  2212. reasoning_block = content_blocks[-1]
  2213. reasoning_block["content"] += reasoning_content
  2214. data = {
  2215. "content": serialize_content_blocks(
  2216. content_blocks
  2217. )
  2218. }
  2219. if value:
  2220. if (
  2221. content_blocks
  2222. and content_blocks[-1]["type"]
  2223. == "reasoning"
  2224. and content_blocks[-1]
  2225. .get("attributes", {})
  2226. .get("type")
  2227. == "reasoning_content"
  2228. ):
  2229. reasoning_block = content_blocks[-1]
  2230. reasoning_block["ended_at"] = time.time()
  2231. reasoning_block["duration"] = int(
  2232. reasoning_block["ended_at"]
  2233. - reasoning_block["started_at"]
  2234. )
  2235. content_blocks.append(
  2236. {
  2237. "type": "text",
  2238. "content": "",
  2239. }
  2240. )
  2241. content = f"{content}{value}"
  2242. if not content_blocks:
  2243. content_blocks.append(
  2244. {
  2245. "type": "text",
  2246. "content": "",
  2247. }
  2248. )
  2249. content_blocks[-1]["content"] = (
  2250. content_blocks[-1]["content"] + value
  2251. )
  2252. if DETECT_REASONING_TAGS:
  2253. content, content_blocks, _ = (
  2254. tag_content_handler(
  2255. "reasoning",
  2256. reasoning_tags,
  2257. content,
  2258. content_blocks,
  2259. )
  2260. )
  2261. content, content_blocks, _ = (
  2262. tag_content_handler(
  2263. "solution",
  2264. DEFAULT_SOLUTION_TAGS,
  2265. content,
  2266. content_blocks,
  2267. )
  2268. )
  2269. if DETECT_CODE_INTERPRETER:
  2270. content, content_blocks, end = (
  2271. tag_content_handler(
  2272. "code_interpreter",
  2273. DEFAULT_CODE_INTERPRETER_TAGS,
  2274. content,
  2275. content_blocks,
  2276. )
  2277. )
  2278. if end:
  2279. break
  2280. if ENABLE_REALTIME_CHAT_SAVE:
  2281. # Save message in the database
  2282. Chats.upsert_message_to_chat_by_id_and_message_id(
  2283. metadata["chat_id"],
  2284. metadata["message_id"],
  2285. {
  2286. "content": serialize_content_blocks(
  2287. content_blocks
  2288. ),
  2289. },
  2290. )
  2291. else:
  2292. data = {
  2293. "content": serialize_content_blocks(
  2294. content_blocks
  2295. ),
  2296. }
  2297. if delta:
  2298. delta_count += 1
  2299. last_delta_data = data
  2300. if delta_count >= delta_chunk_size:
  2301. await flush_pending_delta_data(delta_chunk_size)
  2302. else:
  2303. await event_emitter(
  2304. {
  2305. "type": "chat:completion",
  2306. "data": data,
  2307. }
  2308. )
  2309. except Exception as e:
  2310. done = "data: [DONE]" in line
  2311. if done:
  2312. pass
  2313. else:
  2314. log.debug(f"Error: {e}")
  2315. continue
  2316. await flush_pending_delta_data()
  2317. if content_blocks:
  2318. # Clean up the last text block
  2319. if content_blocks[-1]["type"] == "text":
  2320. content_blocks[-1]["content"] = content_blocks[-1][
  2321. "content"
  2322. ].strip()
  2323. if not content_blocks[-1]["content"]:
  2324. content_blocks.pop()
  2325. if not content_blocks:
  2326. content_blocks.append(
  2327. {
  2328. "type": "text",
  2329. "content": "",
  2330. }
  2331. )
  2332. if content_blocks[-1]["type"] == "reasoning":
  2333. reasoning_block = content_blocks[-1]
  2334. if reasoning_block.get("ended_at") is None:
  2335. reasoning_block["ended_at"] = time.time()
  2336. reasoning_block["duration"] = int(
  2337. reasoning_block["ended_at"]
  2338. - reasoning_block["started_at"]
  2339. )
  2340. if response_tool_calls:
  2341. tool_calls.append(response_tool_calls)
  2342. if response.background:
  2343. await response.background()
  2344. await stream_body_handler(response, form_data)
  2345. tool_call_retries = 0
  2346. while (
  2347. len(tool_calls) > 0
  2348. and tool_call_retries < CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES
  2349. ):
  2350. tool_call_retries += 1
  2351. response_tool_calls = tool_calls.pop(0)
  2352. content_blocks.append(
  2353. {
  2354. "type": "tool_calls",
  2355. "content": response_tool_calls,
  2356. }
  2357. )
  2358. await event_emitter(
  2359. {
  2360. "type": "chat:completion",
  2361. "data": {
  2362. "content": serialize_content_blocks(content_blocks),
  2363. },
  2364. }
  2365. )
  2366. tools = metadata.get("tools", {})
  2367. results = []
  2368. for tool_call in response_tool_calls:
  2369. tool_call_id = tool_call.get("id", "")
  2370. tool_function_name = tool_call.get("function", {}).get(
  2371. "name", ""
  2372. )
  2373. tool_args = tool_call.get("function", {}).get("arguments", "{}")
  2374. tool_function_params = {}
  2375. try:
  2376. # json.loads cannot be used because some models do not produce valid JSON
  2377. tool_function_params = ast.literal_eval(tool_args)
  2378. except Exception as e:
  2379. log.debug(e)
  2380. # Fallback to JSON parsing
  2381. try:
  2382. tool_function_params = json.loads(tool_args)
  2383. except Exception as e:
  2384. log.error(
  2385. f"Error parsing tool call arguments: {tool_args}"
  2386. )
  2387. # Mutate the original tool call response params as they are passed back to the passed
  2388. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  2389. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  2390. # params are not valid json.
  2391. # Main case so far is no args = "" = invalid json.
  2392. log.debug(
  2393. f"Parsed args from {tool_args} to {tool_function_params}"
  2394. )
  2395. tool_call.setdefault("function", {})["arguments"] = json.dumps(
  2396. tool_function_params
  2397. )
  2398. tool_result = None
  2399. tool = None
  2400. tool_type = None
  2401. direct_tool = False
  2402. if tool_function_name in tools:
  2403. tool = tools[tool_function_name]
  2404. spec = tool.get("spec", {})
  2405. tool_type = tool.get("type", "")
  2406. direct_tool = tool.get("direct", False)
  2407. try:
  2408. allowed_params = (
  2409. spec.get("parameters", {})
  2410. .get("properties", {})
  2411. .keys()
  2412. )
  2413. tool_function_params = {
  2414. k: v
  2415. for k, v in tool_function_params.items()
  2416. if k in allowed_params
  2417. }
  2418. if direct_tool:
  2419. tool_result = await event_caller(
  2420. {
  2421. "type": "execute:tool",
  2422. "data": {
  2423. "id": str(uuid4()),
  2424. "name": tool_function_name,
  2425. "params": tool_function_params,
  2426. "server": tool.get("server", {}),
  2427. "session_id": metadata.get(
  2428. "session_id", None
  2429. ),
  2430. },
  2431. }
  2432. )
  2433. else:
  2434. tool_function = await get_updated_tool_function(
  2435. function=tool["callable"],
  2436. extra_params={
  2437. "__messages__": form_data.get(
  2438. "messages", []
  2439. ),
  2440. "__files__": metadata.get("files", []),
  2441. },
  2442. )
  2443. tool_result = await tool_function(
  2444. **tool_function_params
  2445. )
  2446. except Exception as e:
  2447. tool_result = str(e)
  2448. tool_result, tool_result_files, tool_result_embeds = (
  2449. process_tool_result(
  2450. request,
  2451. tool_function_name,
  2452. tool_result,
  2453. tool_type,
  2454. direct_tool,
  2455. metadata,
  2456. user,
  2457. )
  2458. )
  2459. results.append(
  2460. {
  2461. "tool_call_id": tool_call_id,
  2462. "content": tool_result or "",
  2463. **(
  2464. {"files": tool_result_files}
  2465. if tool_result_files
  2466. else {}
  2467. ),
  2468. **(
  2469. {"embeds": tool_result_embeds}
  2470. if tool_result_embeds
  2471. else {}
  2472. ),
  2473. }
  2474. )
  2475. content_blocks[-1]["results"] = results
  2476. content_blocks.append(
  2477. {
  2478. "type": "text",
  2479. "content": "",
  2480. }
  2481. )
  2482. await event_emitter(
  2483. {
  2484. "type": "chat:completion",
  2485. "data": {
  2486. "content": serialize_content_blocks(content_blocks),
  2487. },
  2488. }
  2489. )
  2490. try:
  2491. new_form_data = {
  2492. **form_data,
  2493. "model": model_id,
  2494. "stream": True,
  2495. "messages": [
  2496. *form_data["messages"],
  2497. *convert_content_blocks_to_messages(
  2498. content_blocks, True
  2499. ),
  2500. ],
  2501. }
  2502. res = await generate_chat_completion(
  2503. request,
  2504. new_form_data,
  2505. user,
  2506. )
  2507. if isinstance(res, StreamingResponse):
  2508. await stream_body_handler(res, new_form_data)
  2509. else:
  2510. break
  2511. except Exception as e:
  2512. log.debug(e)
  2513. break
  2514. if DETECT_CODE_INTERPRETER:
  2515. MAX_RETRIES = 5
  2516. retries = 0
  2517. while (
  2518. content_blocks[-1]["type"] == "code_interpreter"
  2519. and retries < MAX_RETRIES
  2520. ):
  2521. await event_emitter(
  2522. {
  2523. "type": "chat:completion",
  2524. "data": {
  2525. "content": serialize_content_blocks(content_blocks),
  2526. },
  2527. }
  2528. )
  2529. retries += 1
  2530. log.debug(f"Attempt count: {retries}")
  2531. output = ""
  2532. try:
  2533. if content_blocks[-1]["attributes"].get("type") == "code":
  2534. code = content_blocks[-1]["content"]
  2535. if CODE_INTERPRETER_BLOCKED_MODULES:
  2536. blocking_code = textwrap.dedent(
  2537. f"""
  2538. import builtins
  2539. BLOCKED_MODULES = {CODE_INTERPRETER_BLOCKED_MODULES}
  2540. _real_import = builtins.__import__
  2541. def restricted_import(name, globals=None, locals=None, fromlist=(), level=0):
  2542. if name.split('.')[0] in BLOCKED_MODULES:
  2543. importer_name = globals.get('__name__') if globals else None
  2544. if importer_name == '__main__':
  2545. raise ImportError(
  2546. f"Direct import of module {{name}} is restricted."
  2547. )
  2548. return _real_import(name, globals, locals, fromlist, level)
  2549. builtins.__import__ = restricted_import
  2550. """
  2551. )
  2552. code = blocking_code + "\n" + code
  2553. if (
  2554. request.app.state.config.CODE_INTERPRETER_ENGINE
  2555. == "pyodide"
  2556. ):
  2557. output = await event_caller(
  2558. {
  2559. "type": "execute:python",
  2560. "data": {
  2561. "id": str(uuid4()),
  2562. "code": code,
  2563. "session_id": metadata.get(
  2564. "session_id", None
  2565. ),
  2566. },
  2567. }
  2568. )
  2569. elif (
  2570. request.app.state.config.CODE_INTERPRETER_ENGINE
  2571. == "jupyter"
  2572. ):
  2573. output = await execute_code_jupyter(
  2574. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  2575. code,
  2576. (
  2577. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  2578. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2579. == "token"
  2580. else None
  2581. ),
  2582. (
  2583. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  2584. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2585. == "password"
  2586. else None
  2587. ),
  2588. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  2589. )
  2590. else:
  2591. output = {
  2592. "stdout": "Code interpreter engine not configured."
  2593. }
  2594. log.debug(f"Code interpreter output: {output}")
  2595. if isinstance(output, dict):
  2596. stdout = output.get("stdout", "")
  2597. if isinstance(stdout, str):
  2598. stdoutLines = stdout.split("\n")
  2599. for idx, line in enumerate(stdoutLines):
  2600. if "data:image/png;base64" in line:
  2601. image_url = get_image_url_from_base64(
  2602. request,
  2603. line,
  2604. metadata,
  2605. user,
  2606. )
  2607. if image_url:
  2608. stdoutLines[idx] = (
  2609. f"![Output Image]({image_url})"
  2610. )
  2611. output["stdout"] = "\n".join(stdoutLines)
  2612. result = output.get("result", "")
  2613. if isinstance(result, str):
  2614. resultLines = result.split("\n")
  2615. for idx, line in enumerate(resultLines):
  2616. if "data:image/png;base64" in line:
  2617. image_url = get_image_url_from_base64(
  2618. request,
  2619. line,
  2620. metadata,
  2621. user,
  2622. )
  2623. resultLines[idx] = (
  2624. f"![Output Image]({image_url})"
  2625. )
  2626. output["result"] = "\n".join(resultLines)
  2627. except Exception as e:
  2628. output = str(e)
  2629. content_blocks[-1]["output"] = output
  2630. content_blocks.append(
  2631. {
  2632. "type": "text",
  2633. "content": "",
  2634. }
  2635. )
  2636. await event_emitter(
  2637. {
  2638. "type": "chat:completion",
  2639. "data": {
  2640. "content": serialize_content_blocks(content_blocks),
  2641. },
  2642. }
  2643. )
  2644. try:
  2645. new_form_data = {
  2646. **form_data,
  2647. "model": model_id,
  2648. "stream": True,
  2649. "messages": [
  2650. *form_data["messages"],
  2651. {
  2652. "role": "assistant",
  2653. "content": serialize_content_blocks(
  2654. content_blocks, raw=True
  2655. ),
  2656. },
  2657. ],
  2658. }
  2659. res = await generate_chat_completion(
  2660. request,
  2661. new_form_data,
  2662. user,
  2663. )
  2664. if isinstance(res, StreamingResponse):
  2665. await stream_body_handler(res, new_form_data)
  2666. else:
  2667. break
  2668. except Exception as e:
  2669. log.debug(e)
  2670. break
  2671. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  2672. data = {
  2673. "done": True,
  2674. "content": serialize_content_blocks(content_blocks),
  2675. "title": title,
  2676. }
  2677. if not ENABLE_REALTIME_CHAT_SAVE:
  2678. # Save message in the database
  2679. Chats.upsert_message_to_chat_by_id_and_message_id(
  2680. metadata["chat_id"],
  2681. metadata["message_id"],
  2682. {
  2683. "content": serialize_content_blocks(content_blocks),
  2684. },
  2685. )
  2686. # Send a webhook notification if the user is not active
  2687. if not get_active_status_by_user_id(user.id):
  2688. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  2689. if webhook_url:
  2690. await post_webhook(
  2691. request.app.state.WEBUI_NAME,
  2692. webhook_url,
  2693. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  2694. {
  2695. "action": "chat",
  2696. "message": content,
  2697. "title": title,
  2698. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  2699. },
  2700. )
  2701. await event_emitter(
  2702. {
  2703. "type": "chat:completion",
  2704. "data": data,
  2705. }
  2706. )
  2707. await background_tasks_handler()
  2708. except asyncio.CancelledError:
  2709. log.warning("Task was cancelled!")
  2710. await event_emitter({"type": "chat:tasks:cancel"})
  2711. if not ENABLE_REALTIME_CHAT_SAVE:
  2712. # Save message in the database
  2713. Chats.upsert_message_to_chat_by_id_and_message_id(
  2714. metadata["chat_id"],
  2715. metadata["message_id"],
  2716. {
  2717. "content": serialize_content_blocks(content_blocks),
  2718. },
  2719. )
  2720. if response.background is not None:
  2721. await response.background()
  2722. return await response_handler(response, events)
  2723. else:
  2724. # Fallback to the original response
  2725. async def stream_wrapper(original_generator, events):
  2726. def wrap_item(item):
  2727. return f"data: {item}\n\n"
  2728. for event in events:
  2729. event, _ = await process_filter_functions(
  2730. request=request,
  2731. filter_functions=filter_functions,
  2732. filter_type="stream",
  2733. form_data=event,
  2734. extra_params=extra_params,
  2735. )
  2736. if event:
  2737. yield wrap_item(json.dumps(event))
  2738. async for data in original_generator:
  2739. data, _ = await process_filter_functions(
  2740. request=request,
  2741. filter_functions=filter_functions,
  2742. filter_type="stream",
  2743. form_data=data,
  2744. extra_params=extra_params,
  2745. )
  2746. if data:
  2747. yield data
  2748. return StreamingResponse(
  2749. stream_wrapper(response.body_iterator, events),
  2750. headers=dict(response.headers),
  2751. background=response.background,
  2752. )