middleware.py 120 KB

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