middleware.py 120 KB

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