1
0

middleware.py 102 KB

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