middleware.py 97 KB

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