middleware.py 121 KB

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