middleware.py 95 KB

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