1
0

middleware.py 129 KB

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