1
0

middleware.py 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605
  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. # Workaround for Ollama 2.0+ system prompt issue
  838. # TODO: replace with add_or_update_system_message
  839. if model.get("owned_by") == "ollama":
  840. form_data["messages"] = prepend_to_first_user_message_content(
  841. rag_template(
  842. request.app.state.config.RAG_TEMPLATE,
  843. context_string,
  844. prompt,
  845. ),
  846. form_data["messages"],
  847. )
  848. else:
  849. form_data["messages"] = add_or_update_system_message(
  850. rag_template(
  851. request.app.state.config.RAG_TEMPLATE,
  852. context_string,
  853. prompt,
  854. ),
  855. form_data["messages"],
  856. )
  857. # If there are citations, add them to the data_items
  858. sources = [
  859. source
  860. for source in sources
  861. if source.get("source", {}).get("name", "")
  862. or source.get("source", {}).get("id", "")
  863. ]
  864. if len(sources) > 0:
  865. events.append({"sources": sources})
  866. if model_knowledge:
  867. await event_emitter(
  868. {
  869. "type": "status",
  870. "data": {
  871. "action": "knowledge_search",
  872. "query": user_message,
  873. "done": True,
  874. "hidden": True,
  875. },
  876. }
  877. )
  878. return form_data, metadata, events
  879. async def process_chat_response(
  880. request, response, form_data, user, metadata, model, events, tasks
  881. ):
  882. async def background_tasks_handler():
  883. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  884. message = message_map.get(metadata["message_id"]) if message_map else None
  885. if message:
  886. message_list = get_message_list(message_map, metadata["message_id"])
  887. # Remove details tags and files from the messages.
  888. # as get_message_list creates a new list, it does not affect
  889. # the original messages outside of this handler
  890. messages = []
  891. for message in message_list:
  892. content = message.get("content", "")
  893. if isinstance(content, list):
  894. for item in content:
  895. if item.get("type") == "text":
  896. content = item["text"]
  897. break
  898. if isinstance(content, str):
  899. content = re.sub(
  900. r"<details\b[^>]*>.*?<\/details>|!\[.*?\]\(.*?\)",
  901. "",
  902. content,
  903. flags=re.S | re.I,
  904. ).strip()
  905. messages.append(
  906. {
  907. **message,
  908. "role": message.get(
  909. "role", "assistant"
  910. ), # Safe fallback for missing role
  911. "content": content,
  912. }
  913. )
  914. if tasks and messages:
  915. if (
  916. TASKS.FOLLOW_UP_GENERATION in tasks
  917. and tasks[TASKS.FOLLOW_UP_GENERATION]
  918. ):
  919. res = await generate_follow_ups(
  920. request,
  921. {
  922. "model": message["model"],
  923. "messages": messages,
  924. "message_id": metadata["message_id"],
  925. "chat_id": metadata["chat_id"],
  926. },
  927. user,
  928. )
  929. if res and isinstance(res, dict):
  930. if len(res.get("choices", [])) == 1:
  931. follow_ups_string = (
  932. res.get("choices", [])[0]
  933. .get("message", {})
  934. .get("content", "")
  935. )
  936. else:
  937. follow_ups_string = ""
  938. follow_ups_string = follow_ups_string[
  939. follow_ups_string.find("{") : follow_ups_string.rfind("}")
  940. + 1
  941. ]
  942. try:
  943. follow_ups = json.loads(follow_ups_string).get(
  944. "follow_ups", []
  945. )
  946. Chats.upsert_message_to_chat_by_id_and_message_id(
  947. metadata["chat_id"],
  948. metadata["message_id"],
  949. {
  950. "followUps": follow_ups,
  951. },
  952. )
  953. await event_emitter(
  954. {
  955. "type": "chat:message:follow_ups",
  956. "data": {
  957. "follow_ups": follow_ups,
  958. },
  959. }
  960. )
  961. except Exception as e:
  962. pass
  963. if TASKS.TITLE_GENERATION in tasks:
  964. user_message = get_last_user_message(messages)
  965. if user_message and len(user_message) > 100:
  966. user_message = user_message[:100] + "..."
  967. if tasks[TASKS.TITLE_GENERATION]:
  968. res = await generate_title(
  969. request,
  970. {
  971. "model": message["model"],
  972. "messages": messages,
  973. "chat_id": metadata["chat_id"],
  974. },
  975. user,
  976. )
  977. if res and isinstance(res, dict):
  978. if len(res.get("choices", [])) == 1:
  979. title_string = (
  980. res.get("choices", [])[0]
  981. .get("message", {})
  982. .get(
  983. "content", message.get("content", user_message)
  984. )
  985. )
  986. else:
  987. title_string = ""
  988. title_string = title_string[
  989. title_string.find("{") : title_string.rfind("}") + 1
  990. ]
  991. try:
  992. title = json.loads(title_string).get(
  993. "title", user_message
  994. )
  995. except Exception as e:
  996. title = ""
  997. if not title:
  998. title = messages[0].get("content", user_message)
  999. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1000. await event_emitter(
  1001. {
  1002. "type": "chat:title",
  1003. "data": title,
  1004. }
  1005. )
  1006. elif len(messages) == 2:
  1007. title = messages[0].get("content", user_message)
  1008. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1009. await event_emitter(
  1010. {
  1011. "type": "chat:title",
  1012. "data": message.get("content", user_message),
  1013. }
  1014. )
  1015. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  1016. res = await generate_chat_tags(
  1017. request,
  1018. {
  1019. "model": message["model"],
  1020. "messages": messages,
  1021. "chat_id": metadata["chat_id"],
  1022. },
  1023. user,
  1024. )
  1025. if res and isinstance(res, dict):
  1026. if len(res.get("choices", [])) == 1:
  1027. tags_string = (
  1028. res.get("choices", [])[0]
  1029. .get("message", {})
  1030. .get("content", "")
  1031. )
  1032. else:
  1033. tags_string = ""
  1034. tags_string = tags_string[
  1035. tags_string.find("{") : tags_string.rfind("}") + 1
  1036. ]
  1037. try:
  1038. tags = json.loads(tags_string).get("tags", [])
  1039. Chats.update_chat_tags_by_id(
  1040. metadata["chat_id"], tags, user
  1041. )
  1042. await event_emitter(
  1043. {
  1044. "type": "chat:tags",
  1045. "data": tags,
  1046. }
  1047. )
  1048. except Exception as e:
  1049. pass
  1050. event_emitter = None
  1051. event_caller = None
  1052. if (
  1053. "session_id" in metadata
  1054. and metadata["session_id"]
  1055. and "chat_id" in metadata
  1056. and metadata["chat_id"]
  1057. and "message_id" in metadata
  1058. and metadata["message_id"]
  1059. ):
  1060. event_emitter = get_event_emitter(metadata)
  1061. event_caller = get_event_call(metadata)
  1062. # Non-streaming response
  1063. if not isinstance(response, StreamingResponse):
  1064. if event_emitter:
  1065. if isinstance(response, dict) or isinstance(response, JSONResponse):
  1066. if isinstance(response, JSONResponse) and isinstance(
  1067. response.body, bytes
  1068. ):
  1069. try:
  1070. response_data = json.loads(response.body.decode("utf-8"))
  1071. except json.JSONDecodeError:
  1072. response_data = {"error": {"detail": "Invalid JSON response"}}
  1073. else:
  1074. response_data = response
  1075. if "error" in response_data:
  1076. error = response_data["error"].get("detail", response_data["error"])
  1077. Chats.upsert_message_to_chat_by_id_and_message_id(
  1078. metadata["chat_id"],
  1079. metadata["message_id"],
  1080. {
  1081. "error": {"content": error},
  1082. },
  1083. )
  1084. if "selected_model_id" in response_data:
  1085. Chats.upsert_message_to_chat_by_id_and_message_id(
  1086. metadata["chat_id"],
  1087. metadata["message_id"],
  1088. {
  1089. "selectedModelId": response_data["selected_model_id"],
  1090. },
  1091. )
  1092. choices = response_data.get("choices", [])
  1093. if choices and choices[0].get("message", {}).get("content"):
  1094. content = response_data["choices"][0]["message"]["content"]
  1095. if content:
  1096. await event_emitter(
  1097. {
  1098. "type": "chat:completion",
  1099. "data": response_data,
  1100. }
  1101. )
  1102. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1103. await event_emitter(
  1104. {
  1105. "type": "chat:completion",
  1106. "data": {
  1107. "done": True,
  1108. "content": content,
  1109. "title": title,
  1110. },
  1111. }
  1112. )
  1113. # Save message in the database
  1114. Chats.upsert_message_to_chat_by_id_and_message_id(
  1115. metadata["chat_id"],
  1116. metadata["message_id"],
  1117. {
  1118. "role": "assistant",
  1119. "content": content,
  1120. },
  1121. )
  1122. # Send a webhook notification if the user is not active
  1123. if not get_active_status_by_user_id(user.id):
  1124. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1125. if webhook_url:
  1126. await post_webhook(
  1127. request.app.state.WEBUI_NAME,
  1128. webhook_url,
  1129. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1130. {
  1131. "action": "chat",
  1132. "message": content,
  1133. "title": title,
  1134. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1135. },
  1136. )
  1137. await background_tasks_handler()
  1138. if events and isinstance(events, list):
  1139. extra_response = {}
  1140. for event in events:
  1141. if isinstance(event, dict):
  1142. extra_response.update(event)
  1143. else:
  1144. extra_response[event] = True
  1145. response_data = {
  1146. **extra_response,
  1147. **response_data,
  1148. }
  1149. if isinstance(response, dict):
  1150. response = response_data
  1151. if isinstance(response, JSONResponse):
  1152. response = JSONResponse(
  1153. content=response_data,
  1154. headers=response.headers,
  1155. status_code=response.status_code,
  1156. )
  1157. return response
  1158. else:
  1159. if events and isinstance(events, list) and isinstance(response, dict):
  1160. extra_response = {}
  1161. for event in events:
  1162. if isinstance(event, dict):
  1163. extra_response.update(event)
  1164. else:
  1165. extra_response[event] = True
  1166. response = {
  1167. **extra_response,
  1168. **response,
  1169. }
  1170. return response
  1171. # Non standard response
  1172. if not any(
  1173. content_type in response.headers["Content-Type"]
  1174. for content_type in ["text/event-stream", "application/x-ndjson"]
  1175. ):
  1176. return response
  1177. extra_params = {
  1178. "__event_emitter__": event_emitter,
  1179. "__event_call__": event_caller,
  1180. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  1181. "__metadata__": metadata,
  1182. "__request__": request,
  1183. "__model__": model,
  1184. }
  1185. filter_functions = [
  1186. Functions.get_function_by_id(filter_id)
  1187. for filter_id in get_sorted_filter_ids(
  1188. request, model, metadata.get("filter_ids", [])
  1189. )
  1190. ]
  1191. # Streaming response
  1192. if event_emitter and event_caller:
  1193. task_id = str(uuid4()) # Create a unique task ID.
  1194. model_id = form_data.get("model", "")
  1195. def split_content_and_whitespace(content):
  1196. content_stripped = content.rstrip()
  1197. original_whitespace = (
  1198. content[len(content_stripped) :]
  1199. if len(content) > len(content_stripped)
  1200. else ""
  1201. )
  1202. return content_stripped, original_whitespace
  1203. def is_opening_code_block(content):
  1204. backtick_segments = content.split("```")
  1205. # Even number of segments means the last backticks are opening a new block
  1206. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  1207. # Handle as a background task
  1208. async def response_handler(response, events):
  1209. def serialize_content_blocks(content_blocks, raw=False):
  1210. content = ""
  1211. for block in content_blocks:
  1212. if block["type"] == "text":
  1213. block_content = block["content"].strip()
  1214. if block_content:
  1215. content = f"{content}{block_content}\n"
  1216. elif block["type"] == "tool_calls":
  1217. attributes = block.get("attributes", {})
  1218. tool_calls = block.get("content", [])
  1219. results = block.get("results", [])
  1220. if content and not content.endswith("\n"):
  1221. content += "\n"
  1222. if results:
  1223. tool_calls_display_content = ""
  1224. for tool_call in tool_calls:
  1225. tool_call_id = tool_call.get("id", "")
  1226. tool_name = tool_call.get("function", {}).get(
  1227. "name", ""
  1228. )
  1229. tool_arguments = tool_call.get("function", {}).get(
  1230. "arguments", ""
  1231. )
  1232. tool_result = None
  1233. tool_result_files = None
  1234. for result in results:
  1235. if tool_call_id == result.get("tool_call_id", ""):
  1236. tool_result = result.get("content", None)
  1237. tool_result_files = result.get("files", None)
  1238. break
  1239. if tool_result:
  1240. 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'
  1241. else:
  1242. 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'
  1243. if not raw:
  1244. content = f"{content}{tool_calls_display_content}"
  1245. else:
  1246. tool_calls_display_content = ""
  1247. for tool_call in tool_calls:
  1248. tool_call_id = tool_call.get("id", "")
  1249. tool_name = tool_call.get("function", {}).get(
  1250. "name", ""
  1251. )
  1252. tool_arguments = tool_call.get("function", {}).get(
  1253. "arguments", ""
  1254. )
  1255. 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'
  1256. if not raw:
  1257. content = f"{content}{tool_calls_display_content}"
  1258. elif block["type"] == "reasoning":
  1259. reasoning_display_content = "\n".join(
  1260. (f"> {line}" if not line.startswith(">") else line)
  1261. for line in block["content"].splitlines()
  1262. )
  1263. reasoning_duration = block.get("duration", None)
  1264. start_tag = block.get("start_tag", "")
  1265. end_tag = block.get("end_tag", "")
  1266. if content and not content.endswith("\n"):
  1267. content += "\n"
  1268. if reasoning_duration is not None:
  1269. if raw:
  1270. content = (
  1271. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1272. )
  1273. else:
  1274. 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'
  1275. else:
  1276. if raw:
  1277. content = (
  1278. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1279. )
  1280. else:
  1281. content = f'{content}<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1282. elif block["type"] == "code_interpreter":
  1283. attributes = block.get("attributes", {})
  1284. output = block.get("output", None)
  1285. lang = attributes.get("lang", "")
  1286. content_stripped, original_whitespace = (
  1287. split_content_and_whitespace(content)
  1288. )
  1289. if is_opening_code_block(content_stripped):
  1290. # Remove trailing backticks that would open a new block
  1291. content = (
  1292. content_stripped.rstrip("`").rstrip()
  1293. + original_whitespace
  1294. )
  1295. else:
  1296. # Keep content as is - either closing backticks or no backticks
  1297. content = content_stripped + original_whitespace
  1298. if content and not content.endswith("\n"):
  1299. content += "\n"
  1300. if output:
  1301. output = html.escape(json.dumps(output))
  1302. if raw:
  1303. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1304. else:
  1305. content = f'{content}<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1306. else:
  1307. if raw:
  1308. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1309. else:
  1310. content = f'{content}<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1311. else:
  1312. block_content = str(block["content"]).strip()
  1313. if block_content:
  1314. content = f"{content}{block['type']}: {block_content}\n"
  1315. return content.strip()
  1316. def convert_content_blocks_to_messages(content_blocks, raw=False):
  1317. messages = []
  1318. temp_blocks = []
  1319. for idx, block in enumerate(content_blocks):
  1320. if block["type"] == "tool_calls":
  1321. messages.append(
  1322. {
  1323. "role": "assistant",
  1324. "content": serialize_content_blocks(temp_blocks, raw),
  1325. "tool_calls": block.get("content"),
  1326. }
  1327. )
  1328. results = block.get("results", [])
  1329. for result in results:
  1330. messages.append(
  1331. {
  1332. "role": "tool",
  1333. "tool_call_id": result["tool_call_id"],
  1334. "content": result["content"],
  1335. }
  1336. )
  1337. temp_blocks = []
  1338. else:
  1339. temp_blocks.append(block)
  1340. if temp_blocks:
  1341. content = serialize_content_blocks(temp_blocks, raw)
  1342. if content:
  1343. messages.append(
  1344. {
  1345. "role": "assistant",
  1346. "content": content,
  1347. }
  1348. )
  1349. return messages
  1350. def tag_content_handler(content_type, tags, content, content_blocks):
  1351. end_flag = False
  1352. def extract_attributes(tag_content):
  1353. """Extract attributes from a tag if they exist."""
  1354. attributes = {}
  1355. if not tag_content: # Ensure tag_content is not None
  1356. return attributes
  1357. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1358. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1359. for key, value in matches:
  1360. attributes[key] = value
  1361. return attributes
  1362. if content_blocks[-1]["type"] == "text":
  1363. for start_tag, end_tag in tags:
  1364. start_tag_pattern = rf"{re.escape(start_tag)}"
  1365. if start_tag.startswith("<") and start_tag.endswith(">"):
  1366. # Match start tag e.g., <tag> or <tag attr="value">
  1367. # remove both '<' and '>' from start_tag
  1368. # Match start tag with attributes
  1369. start_tag_pattern = (
  1370. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1371. )
  1372. match = re.search(start_tag_pattern, content)
  1373. if match:
  1374. try:
  1375. attr_content = (
  1376. match.group(1) if match.group(1) else ""
  1377. ) # Ensure it's not None
  1378. except:
  1379. attr_content = ""
  1380. attributes = extract_attributes(
  1381. attr_content
  1382. ) # Extract attributes safely
  1383. # Capture everything before and after the matched tag
  1384. before_tag = content[
  1385. : match.start()
  1386. ] # Content before opening tag
  1387. after_tag = content[
  1388. match.end() :
  1389. ] # Content after opening tag
  1390. # Remove the start tag and after from the currently handling text block
  1391. content_blocks[-1]["content"] = content_blocks[-1][
  1392. "content"
  1393. ].replace(match.group(0) + after_tag, "")
  1394. if before_tag:
  1395. content_blocks[-1]["content"] = before_tag
  1396. if not content_blocks[-1]["content"]:
  1397. content_blocks.pop()
  1398. # Append the new block
  1399. content_blocks.append(
  1400. {
  1401. "type": content_type,
  1402. "start_tag": start_tag,
  1403. "end_tag": end_tag,
  1404. "attributes": attributes,
  1405. "content": "",
  1406. "started_at": time.time(),
  1407. }
  1408. )
  1409. if after_tag:
  1410. content_blocks[-1]["content"] = after_tag
  1411. tag_content_handler(
  1412. content_type, tags, after_tag, content_blocks
  1413. )
  1414. break
  1415. elif content_blocks[-1]["type"] == content_type:
  1416. start_tag = content_blocks[-1]["start_tag"]
  1417. end_tag = content_blocks[-1]["end_tag"]
  1418. if end_tag.startswith("<") and end_tag.endswith(">"):
  1419. # Match end tag e.g., </tag>
  1420. end_tag_pattern = rf"{re.escape(end_tag)}"
  1421. else:
  1422. # Handle cases where end_tag is just a tag name
  1423. end_tag_pattern = rf"{re.escape(end_tag)}"
  1424. # Check if the content has the end tag
  1425. if re.search(end_tag_pattern, content):
  1426. end_flag = True
  1427. block_content = content_blocks[-1]["content"]
  1428. # Strip start and end tags from the content
  1429. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1430. block_content = re.sub(
  1431. start_tag_pattern, "", block_content
  1432. ).strip()
  1433. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1434. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1435. # Content inside the tag
  1436. block_content = (
  1437. split_content[0].strip() if split_content else ""
  1438. )
  1439. # Leftover content (everything after `</tag>`)
  1440. leftover_content = (
  1441. split_content[1].strip() if len(split_content) > 1 else ""
  1442. )
  1443. if block_content:
  1444. content_blocks[-1]["content"] = block_content
  1445. content_blocks[-1]["ended_at"] = time.time()
  1446. content_blocks[-1]["duration"] = int(
  1447. content_blocks[-1]["ended_at"]
  1448. - content_blocks[-1]["started_at"]
  1449. )
  1450. # Reset the content_blocks by appending a new text block
  1451. if content_type != "code_interpreter":
  1452. if leftover_content:
  1453. content_blocks.append(
  1454. {
  1455. "type": "text",
  1456. "content": leftover_content,
  1457. }
  1458. )
  1459. else:
  1460. content_blocks.append(
  1461. {
  1462. "type": "text",
  1463. "content": "",
  1464. }
  1465. )
  1466. else:
  1467. # Remove the block if content is empty
  1468. content_blocks.pop()
  1469. if leftover_content:
  1470. content_blocks.append(
  1471. {
  1472. "type": "text",
  1473. "content": leftover_content,
  1474. }
  1475. )
  1476. else:
  1477. content_blocks.append(
  1478. {
  1479. "type": "text",
  1480. "content": "",
  1481. }
  1482. )
  1483. # Clean processed content
  1484. start_tag_pattern = rf"{re.escape(start_tag)}"
  1485. if start_tag.startswith("<") and start_tag.endswith(">"):
  1486. # Match start tag e.g., <tag> or <tag attr="value">
  1487. # remove both '<' and '>' from start_tag
  1488. # Match start tag with attributes
  1489. start_tag_pattern = (
  1490. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1491. )
  1492. content = re.sub(
  1493. rf"{start_tag_pattern}(.|\n)*?{re.escape(end_tag)}",
  1494. "",
  1495. content,
  1496. flags=re.DOTALL,
  1497. )
  1498. return content, content_blocks, end_flag
  1499. message = Chats.get_message_by_id_and_message_id(
  1500. metadata["chat_id"], metadata["message_id"]
  1501. )
  1502. tool_calls = []
  1503. last_assistant_message = None
  1504. try:
  1505. if form_data["messages"][-1]["role"] == "assistant":
  1506. last_assistant_message = get_last_assistant_message(
  1507. form_data["messages"]
  1508. )
  1509. except Exception as e:
  1510. pass
  1511. content = (
  1512. message.get("content", "")
  1513. if message
  1514. else last_assistant_message if last_assistant_message else ""
  1515. )
  1516. content_blocks = [
  1517. {
  1518. "type": "text",
  1519. "content": content,
  1520. }
  1521. ]
  1522. # We might want to disable this by default
  1523. DETECT_REASONING = True
  1524. DETECT_SOLUTION = True
  1525. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1526. "code_interpreter", False
  1527. )
  1528. reasoning_tags = [
  1529. ("<think>", "</think>"),
  1530. ("<thinking>", "</thinking>"),
  1531. ("<reason>", "</reason>"),
  1532. ("<reasoning>", "</reasoning>"),
  1533. ("<thought>", "</thought>"),
  1534. ("<Thought>", "</Thought>"),
  1535. ("<|begin_of_thought|>", "<|end_of_thought|>"),
  1536. ("◁think▷", "◁/think▷"),
  1537. ]
  1538. code_interpreter_tags = [("<code_interpreter>", "</code_interpreter>")]
  1539. solution_tags = [("<|begin_of_solution|>", "<|end_of_solution|>")]
  1540. try:
  1541. for event in events:
  1542. await event_emitter(
  1543. {
  1544. "type": "chat:completion",
  1545. "data": event,
  1546. }
  1547. )
  1548. # Save message in the database
  1549. Chats.upsert_message_to_chat_by_id_and_message_id(
  1550. metadata["chat_id"],
  1551. metadata["message_id"],
  1552. {
  1553. **event,
  1554. },
  1555. )
  1556. async def stream_body_handler(response, form_data):
  1557. nonlocal content
  1558. nonlocal content_blocks
  1559. response_tool_calls = []
  1560. delta_count = 0
  1561. delta_chunk_size = max(
  1562. CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
  1563. int(
  1564. metadata.get("params", {}).get("stream_delta_chunk_size")
  1565. or 1
  1566. ),
  1567. )
  1568. async for line in response.body_iterator:
  1569. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1570. data = line
  1571. # Skip empty lines
  1572. if not data.strip():
  1573. continue
  1574. # "data:" is the prefix for each event
  1575. if not data.startswith("data:"):
  1576. continue
  1577. # Remove the prefix
  1578. data = data[len("data:") :].strip()
  1579. try:
  1580. data = json.loads(data)
  1581. data, _ = await process_filter_functions(
  1582. request=request,
  1583. filter_functions=filter_functions,
  1584. filter_type="stream",
  1585. form_data=data,
  1586. extra_params={"__body__": form_data, **extra_params},
  1587. )
  1588. if data:
  1589. if "event" in data:
  1590. await event_emitter(data.get("event", {}))
  1591. if "selected_model_id" in data:
  1592. model_id = data["selected_model_id"]
  1593. Chats.upsert_message_to_chat_by_id_and_message_id(
  1594. metadata["chat_id"],
  1595. metadata["message_id"],
  1596. {
  1597. "selectedModelId": model_id,
  1598. },
  1599. )
  1600. else:
  1601. choices = data.get("choices", [])
  1602. if not choices:
  1603. error = data.get("error", {})
  1604. if error:
  1605. await event_emitter(
  1606. {
  1607. "type": "chat:completion",
  1608. "data": {
  1609. "error": error,
  1610. },
  1611. }
  1612. )
  1613. usage = data.get("usage", {})
  1614. if usage:
  1615. await event_emitter(
  1616. {
  1617. "type": "chat:completion",
  1618. "data": {
  1619. "usage": usage,
  1620. },
  1621. }
  1622. )
  1623. continue
  1624. delta = choices[0].get("delta", {})
  1625. delta_tool_calls = delta.get("tool_calls", None)
  1626. if delta_tool_calls:
  1627. for delta_tool_call in delta_tool_calls:
  1628. tool_call_index = delta_tool_call.get(
  1629. "index"
  1630. )
  1631. if tool_call_index is not None:
  1632. # Check if the tool call already exists
  1633. current_response_tool_call = None
  1634. for (
  1635. response_tool_call
  1636. ) in response_tool_calls:
  1637. if (
  1638. response_tool_call.get("index")
  1639. == tool_call_index
  1640. ):
  1641. current_response_tool_call = (
  1642. response_tool_call
  1643. )
  1644. break
  1645. if current_response_tool_call is None:
  1646. # Add the new tool call
  1647. delta_tool_call.setdefault(
  1648. "function", {}
  1649. )
  1650. delta_tool_call[
  1651. "function"
  1652. ].setdefault("name", "")
  1653. delta_tool_call[
  1654. "function"
  1655. ].setdefault("arguments", "")
  1656. response_tool_calls.append(
  1657. delta_tool_call
  1658. )
  1659. else:
  1660. # Update the existing tool call
  1661. delta_name = delta_tool_call.get(
  1662. "function", {}
  1663. ).get("name")
  1664. delta_arguments = (
  1665. delta_tool_call.get(
  1666. "function", {}
  1667. ).get("arguments")
  1668. )
  1669. if delta_name:
  1670. current_response_tool_call[
  1671. "function"
  1672. ]["name"] += delta_name
  1673. if delta_arguments:
  1674. current_response_tool_call[
  1675. "function"
  1676. ][
  1677. "arguments"
  1678. ] += delta_arguments
  1679. value = delta.get("content")
  1680. reasoning_content = (
  1681. delta.get("reasoning_content")
  1682. or delta.get("reasoning")
  1683. or delta.get("thinking")
  1684. )
  1685. if reasoning_content:
  1686. if (
  1687. not content_blocks
  1688. or content_blocks[-1]["type"] != "reasoning"
  1689. ):
  1690. reasoning_block = {
  1691. "type": "reasoning",
  1692. "start_tag": "<think>",
  1693. "end_tag": "</think>",
  1694. "attributes": {
  1695. "type": "reasoning_content"
  1696. },
  1697. "content": "",
  1698. "started_at": time.time(),
  1699. }
  1700. content_blocks.append(reasoning_block)
  1701. else:
  1702. reasoning_block = content_blocks[-1]
  1703. reasoning_block["content"] += reasoning_content
  1704. data = {
  1705. "content": serialize_content_blocks(
  1706. content_blocks
  1707. )
  1708. }
  1709. if value:
  1710. if (
  1711. content_blocks
  1712. and content_blocks[-1]["type"]
  1713. == "reasoning"
  1714. and content_blocks[-1]
  1715. .get("attributes", {})
  1716. .get("type")
  1717. == "reasoning_content"
  1718. ):
  1719. reasoning_block = content_blocks[-1]
  1720. reasoning_block["ended_at"] = time.time()
  1721. reasoning_block["duration"] = int(
  1722. reasoning_block["ended_at"]
  1723. - reasoning_block["started_at"]
  1724. )
  1725. content_blocks.append(
  1726. {
  1727. "type": "text",
  1728. "content": "",
  1729. }
  1730. )
  1731. content = f"{content}{value}"
  1732. if not content_blocks:
  1733. content_blocks.append(
  1734. {
  1735. "type": "text",
  1736. "content": "",
  1737. }
  1738. )
  1739. content_blocks[-1]["content"] = (
  1740. content_blocks[-1]["content"] + value
  1741. )
  1742. if DETECT_REASONING:
  1743. content, content_blocks, _ = (
  1744. tag_content_handler(
  1745. "reasoning",
  1746. reasoning_tags,
  1747. content,
  1748. content_blocks,
  1749. )
  1750. )
  1751. if DETECT_CODE_INTERPRETER:
  1752. content, content_blocks, end = (
  1753. tag_content_handler(
  1754. "code_interpreter",
  1755. code_interpreter_tags,
  1756. content,
  1757. content_blocks,
  1758. )
  1759. )
  1760. if end:
  1761. break
  1762. if DETECT_SOLUTION:
  1763. content, content_blocks, _ = (
  1764. tag_content_handler(
  1765. "solution",
  1766. solution_tags,
  1767. content,
  1768. content_blocks,
  1769. )
  1770. )
  1771. if ENABLE_REALTIME_CHAT_SAVE:
  1772. # Save message in the database
  1773. Chats.upsert_message_to_chat_by_id_and_message_id(
  1774. metadata["chat_id"],
  1775. metadata["message_id"],
  1776. {
  1777. "content": serialize_content_blocks(
  1778. content_blocks
  1779. ),
  1780. },
  1781. )
  1782. else:
  1783. data = {
  1784. "content": serialize_content_blocks(
  1785. content_blocks
  1786. ),
  1787. }
  1788. if delta:
  1789. delta_count += 1
  1790. if delta_count >= delta_chunk_size:
  1791. await event_emitter(
  1792. {
  1793. "type": "chat:completion",
  1794. "data": data,
  1795. }
  1796. )
  1797. delta_count = 0
  1798. else:
  1799. await event_emitter(
  1800. {
  1801. "type": "chat:completion",
  1802. "data": data,
  1803. }
  1804. )
  1805. except Exception as e:
  1806. done = "data: [DONE]" in line
  1807. if done:
  1808. pass
  1809. else:
  1810. log.debug(f"Error: {e}")
  1811. continue
  1812. if content_blocks:
  1813. # Clean up the last text block
  1814. if content_blocks[-1]["type"] == "text":
  1815. content_blocks[-1]["content"] = content_blocks[-1][
  1816. "content"
  1817. ].strip()
  1818. if not content_blocks[-1]["content"]:
  1819. content_blocks.pop()
  1820. if not content_blocks:
  1821. content_blocks.append(
  1822. {
  1823. "type": "text",
  1824. "content": "",
  1825. }
  1826. )
  1827. if content_blocks[-1]["type"] == "reasoning":
  1828. reasoning_block = content_blocks[-1]
  1829. if reasoning_block.get("ended_at") is None:
  1830. reasoning_block["ended_at"] = time.time()
  1831. reasoning_block["duration"] = int(
  1832. reasoning_block["ended_at"]
  1833. - reasoning_block["started_at"]
  1834. )
  1835. if response_tool_calls:
  1836. tool_calls.append(response_tool_calls)
  1837. if response.background:
  1838. await response.background()
  1839. await stream_body_handler(response, form_data)
  1840. MAX_TOOL_CALL_RETRIES = 10
  1841. tool_call_retries = 0
  1842. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1843. tool_call_retries += 1
  1844. response_tool_calls = tool_calls.pop(0)
  1845. content_blocks.append(
  1846. {
  1847. "type": "tool_calls",
  1848. "content": response_tool_calls,
  1849. }
  1850. )
  1851. await event_emitter(
  1852. {
  1853. "type": "chat:completion",
  1854. "data": {
  1855. "content": serialize_content_blocks(content_blocks),
  1856. },
  1857. }
  1858. )
  1859. tools = metadata.get("tools", {})
  1860. results = []
  1861. for tool_call in response_tool_calls:
  1862. tool_call_id = tool_call.get("id", "")
  1863. tool_name = tool_call.get("function", {}).get("name", "")
  1864. tool_args = tool_call.get("function", {}).get("arguments", "{}")
  1865. tool_function_params = {}
  1866. try:
  1867. # json.loads cannot be used because some models do not produce valid JSON
  1868. tool_function_params = ast.literal_eval(tool_args)
  1869. except Exception as e:
  1870. log.debug(e)
  1871. # Fallback to JSON parsing
  1872. try:
  1873. tool_function_params = json.loads(tool_args)
  1874. except Exception as e:
  1875. log.error(
  1876. f"Error parsing tool call arguments: {tool_args}"
  1877. )
  1878. # Mutate the original tool call response params as they are passed back to the passed
  1879. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  1880. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  1881. # params are not valid json.
  1882. # Main case so far is no args = "" = invalid json.
  1883. log.debug(
  1884. f"Parsed args from {tool_args} to {tool_function_params}"
  1885. )
  1886. tool_call.setdefault("function", {})["arguments"] = json.dumps(
  1887. tool_function_params
  1888. )
  1889. tool_result = None
  1890. if tool_name in tools:
  1891. tool = tools[tool_name]
  1892. spec = tool.get("spec", {})
  1893. try:
  1894. allowed_params = (
  1895. spec.get("parameters", {})
  1896. .get("properties", {})
  1897. .keys()
  1898. )
  1899. tool_function_params = {
  1900. k: v
  1901. for k, v in tool_function_params.items()
  1902. if k in allowed_params
  1903. }
  1904. if tool.get("direct", False):
  1905. tool_result = await event_caller(
  1906. {
  1907. "type": "execute:tool",
  1908. "data": {
  1909. "id": str(uuid4()),
  1910. "name": tool_name,
  1911. "params": tool_function_params,
  1912. "server": tool.get("server", {}),
  1913. "session_id": metadata.get(
  1914. "session_id", None
  1915. ),
  1916. },
  1917. }
  1918. )
  1919. else:
  1920. tool_function = tool["callable"]
  1921. tool_result = await tool_function(
  1922. **tool_function_params
  1923. )
  1924. except Exception as e:
  1925. tool_result = str(e)
  1926. tool_result_files = []
  1927. if isinstance(tool_result, list):
  1928. for item in tool_result:
  1929. # check if string
  1930. if isinstance(item, str) and item.startswith("data:"):
  1931. tool_result_files.append(item)
  1932. tool_result.remove(item)
  1933. if isinstance(tool_result, dict) or isinstance(
  1934. tool_result, list
  1935. ):
  1936. tool_result = json.dumps(
  1937. tool_result, indent=2, ensure_ascii=False
  1938. )
  1939. results.append(
  1940. {
  1941. "tool_call_id": tool_call_id,
  1942. "content": tool_result,
  1943. **(
  1944. {"files": tool_result_files}
  1945. if tool_result_files
  1946. else {}
  1947. ),
  1948. }
  1949. )
  1950. content_blocks[-1]["results"] = results
  1951. content_blocks.append(
  1952. {
  1953. "type": "text",
  1954. "content": "",
  1955. }
  1956. )
  1957. await event_emitter(
  1958. {
  1959. "type": "chat:completion",
  1960. "data": {
  1961. "content": serialize_content_blocks(content_blocks),
  1962. },
  1963. }
  1964. )
  1965. try:
  1966. new_form_data = {
  1967. "model": model_id,
  1968. "stream": True,
  1969. "tools": form_data["tools"],
  1970. "messages": [
  1971. *form_data["messages"],
  1972. *convert_content_blocks_to_messages(
  1973. content_blocks, True
  1974. ),
  1975. ],
  1976. }
  1977. res = await generate_chat_completion(
  1978. request,
  1979. new_form_data,
  1980. user,
  1981. )
  1982. if isinstance(res, StreamingResponse):
  1983. await stream_body_handler(res, new_form_data)
  1984. else:
  1985. break
  1986. except Exception as e:
  1987. log.debug(e)
  1988. break
  1989. if DETECT_CODE_INTERPRETER:
  1990. MAX_RETRIES = 5
  1991. retries = 0
  1992. while (
  1993. content_blocks[-1]["type"] == "code_interpreter"
  1994. and retries < MAX_RETRIES
  1995. ):
  1996. await event_emitter(
  1997. {
  1998. "type": "chat:completion",
  1999. "data": {
  2000. "content": serialize_content_blocks(content_blocks),
  2001. },
  2002. }
  2003. )
  2004. retries += 1
  2005. log.debug(f"Attempt count: {retries}")
  2006. output = ""
  2007. try:
  2008. if content_blocks[-1]["attributes"].get("type") == "code":
  2009. code = content_blocks[-1]["content"]
  2010. if (
  2011. request.app.state.config.CODE_INTERPRETER_ENGINE
  2012. == "pyodide"
  2013. ):
  2014. output = await event_caller(
  2015. {
  2016. "type": "execute:python",
  2017. "data": {
  2018. "id": str(uuid4()),
  2019. "code": code,
  2020. "session_id": metadata.get(
  2021. "session_id", None
  2022. ),
  2023. },
  2024. }
  2025. )
  2026. elif (
  2027. request.app.state.config.CODE_INTERPRETER_ENGINE
  2028. == "jupyter"
  2029. ):
  2030. output = await execute_code_jupyter(
  2031. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  2032. code,
  2033. (
  2034. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  2035. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2036. == "token"
  2037. else None
  2038. ),
  2039. (
  2040. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  2041. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2042. == "password"
  2043. else None
  2044. ),
  2045. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  2046. )
  2047. else:
  2048. output = {
  2049. "stdout": "Code interpreter engine not configured."
  2050. }
  2051. log.debug(f"Code interpreter output: {output}")
  2052. if isinstance(output, dict):
  2053. stdout = output.get("stdout", "")
  2054. if isinstance(stdout, str):
  2055. stdoutLines = stdout.split("\n")
  2056. for idx, line in enumerate(stdoutLines):
  2057. if "data:image/png;base64" in line:
  2058. image_url = ""
  2059. # Extract base64 image data from the line
  2060. image_data, content_type = (
  2061. load_b64_image_data(line)
  2062. )
  2063. if image_data is not None:
  2064. image_url = upload_image(
  2065. request,
  2066. image_data,
  2067. content_type,
  2068. metadata,
  2069. user,
  2070. )
  2071. stdoutLines[idx] = (
  2072. f"![Output Image]({image_url})"
  2073. )
  2074. output["stdout"] = "\n".join(stdoutLines)
  2075. result = output.get("result", "")
  2076. if isinstance(result, str):
  2077. resultLines = result.split("\n")
  2078. for idx, line in enumerate(resultLines):
  2079. if "data:image/png;base64" in line:
  2080. image_url = ""
  2081. # Extract base64 image data from the line
  2082. image_data, content_type = (
  2083. load_b64_image_data(line)
  2084. )
  2085. if image_data is not None:
  2086. image_url = upload_image(
  2087. request,
  2088. image_data,
  2089. content_type,
  2090. metadata,
  2091. user,
  2092. )
  2093. resultLines[idx] = (
  2094. f"![Output Image]({image_url})"
  2095. )
  2096. output["result"] = "\n".join(resultLines)
  2097. except Exception as e:
  2098. output = str(e)
  2099. content_blocks[-1]["output"] = output
  2100. content_blocks.append(
  2101. {
  2102. "type": "text",
  2103. "content": "",
  2104. }
  2105. )
  2106. await event_emitter(
  2107. {
  2108. "type": "chat:completion",
  2109. "data": {
  2110. "content": serialize_content_blocks(content_blocks),
  2111. },
  2112. }
  2113. )
  2114. try:
  2115. new_form_data = {
  2116. "model": model_id,
  2117. "stream": True,
  2118. "messages": [
  2119. *form_data["messages"],
  2120. {
  2121. "role": "assistant",
  2122. "content": serialize_content_blocks(
  2123. content_blocks, raw=True
  2124. ),
  2125. },
  2126. ],
  2127. }
  2128. res = await generate_chat_completion(
  2129. request,
  2130. new_form_data,
  2131. user,
  2132. )
  2133. if isinstance(res, StreamingResponse):
  2134. await stream_body_handler(res, new_form_data)
  2135. else:
  2136. break
  2137. except Exception as e:
  2138. log.debug(e)
  2139. break
  2140. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  2141. data = {
  2142. "done": True,
  2143. "content": serialize_content_blocks(content_blocks),
  2144. "title": title,
  2145. }
  2146. if not ENABLE_REALTIME_CHAT_SAVE:
  2147. # Save message in the database
  2148. Chats.upsert_message_to_chat_by_id_and_message_id(
  2149. metadata["chat_id"],
  2150. metadata["message_id"],
  2151. {
  2152. "content": serialize_content_blocks(content_blocks),
  2153. },
  2154. )
  2155. # Send a webhook notification if the user is not active
  2156. if not get_active_status_by_user_id(user.id):
  2157. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  2158. if webhook_url:
  2159. await post_webhook(
  2160. request.app.state.WEBUI_NAME,
  2161. webhook_url,
  2162. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  2163. {
  2164. "action": "chat",
  2165. "message": content,
  2166. "title": title,
  2167. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  2168. },
  2169. )
  2170. await event_emitter(
  2171. {
  2172. "type": "chat:completion",
  2173. "data": data,
  2174. }
  2175. )
  2176. await background_tasks_handler()
  2177. except asyncio.CancelledError:
  2178. log.warning("Task was cancelled!")
  2179. await event_emitter({"type": "task-cancelled"})
  2180. if not ENABLE_REALTIME_CHAT_SAVE:
  2181. # Save message in the database
  2182. Chats.upsert_message_to_chat_by_id_and_message_id(
  2183. metadata["chat_id"],
  2184. metadata["message_id"],
  2185. {
  2186. "content": serialize_content_blocks(content_blocks),
  2187. },
  2188. )
  2189. if response.background is not None:
  2190. await response.background()
  2191. # background_tasks.add_task(response_handler, response, events)
  2192. task_id, _ = await create_task(
  2193. request.app.state.redis,
  2194. response_handler(response, events),
  2195. id=metadata["chat_id"],
  2196. )
  2197. return {"status": True, "task_id": task_id}
  2198. else:
  2199. # Fallback to the original response
  2200. async def stream_wrapper(original_generator, events):
  2201. def wrap_item(item):
  2202. return f"data: {item}\n\n"
  2203. for event in events:
  2204. event, _ = await process_filter_functions(
  2205. request=request,
  2206. filter_functions=filter_functions,
  2207. filter_type="stream",
  2208. form_data=event,
  2209. extra_params=extra_params,
  2210. )
  2211. if event:
  2212. yield wrap_item(json.dumps(event))
  2213. async for data in original_generator:
  2214. data, _ = await process_filter_functions(
  2215. request=request,
  2216. filter_functions=filter_functions,
  2217. filter_type="stream",
  2218. form_data=data,
  2219. extra_params=extra_params,
  2220. )
  2221. if data:
  2222. yield data
  2223. return StreamingResponse(
  2224. stream_wrapper(response.body_iterator, events),
  2225. headers=dict(response.headers),
  2226. background=response.background,
  2227. )