middleware.py 120 KB

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