middleware.py 120 KB

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