middleware.py 99 KB

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