middleware.py 115 KB

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