middleware.py 104 KB

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