middleware.py 122 KB

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