middleware.py 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560
  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. block_content = block["content"].strip()
  1195. if block_content:
  1196. content = f"{content}{block_content}\n"
  1197. elif block["type"] == "tool_calls":
  1198. attributes = block.get("attributes", {})
  1199. tool_calls = block.get("content", [])
  1200. results = block.get("results", [])
  1201. if content and not content.endswith("\n"):
  1202. content += "\n"
  1203. if results:
  1204. tool_calls_display_content = ""
  1205. for tool_call in tool_calls:
  1206. tool_call_id = tool_call.get("id", "")
  1207. tool_name = tool_call.get("function", {}).get(
  1208. "name", ""
  1209. )
  1210. tool_arguments = tool_call.get("function", {}).get(
  1211. "arguments", ""
  1212. )
  1213. tool_result = None
  1214. tool_result_files = None
  1215. for result in results:
  1216. if tool_call_id == result.get("tool_call_id", ""):
  1217. tool_result = result.get("content", None)
  1218. tool_result_files = result.get("files", None)
  1219. break
  1220. if tool_result:
  1221. 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'
  1222. else:
  1223. 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'
  1224. if not raw:
  1225. content = f"{content}{tool_calls_display_content}"
  1226. else:
  1227. tool_calls_display_content = ""
  1228. for tool_call in tool_calls:
  1229. tool_call_id = tool_call.get("id", "")
  1230. tool_name = tool_call.get("function", {}).get(
  1231. "name", ""
  1232. )
  1233. tool_arguments = tool_call.get("function", {}).get(
  1234. "arguments", ""
  1235. )
  1236. 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'
  1237. if not raw:
  1238. content = f"{content}{tool_calls_display_content}"
  1239. elif block["type"] == "reasoning":
  1240. reasoning_display_content = "\n".join(
  1241. (f"> {line}" if not line.startswith(">") else line)
  1242. for line in block["content"].splitlines()
  1243. )
  1244. reasoning_duration = block.get("duration", None)
  1245. start_tag = block.get("start_tag", "")
  1246. end_tag = block.get("end_tag", "")
  1247. if content and not content.endswith("\n"):
  1248. content += "\n"
  1249. if reasoning_duration is not None:
  1250. if raw:
  1251. content = (
  1252. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1253. )
  1254. else:
  1255. 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'
  1256. else:
  1257. if raw:
  1258. content = (
  1259. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1260. )
  1261. else:
  1262. content = f'{content}<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1263. elif block["type"] == "code_interpreter":
  1264. attributes = block.get("attributes", {})
  1265. output = block.get("output", None)
  1266. lang = attributes.get("lang", "")
  1267. content_stripped, original_whitespace = (
  1268. split_content_and_whitespace(content)
  1269. )
  1270. if is_opening_code_block(content_stripped):
  1271. # Remove trailing backticks that would open a new block
  1272. content = (
  1273. content_stripped.rstrip("`").rstrip()
  1274. + original_whitespace
  1275. )
  1276. else:
  1277. # Keep content as is - either closing backticks or no backticks
  1278. content = content_stripped + original_whitespace
  1279. if content and not content.endswith("\n"):
  1280. content += "\n"
  1281. if output:
  1282. output = html.escape(json.dumps(output))
  1283. if raw:
  1284. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1285. else:
  1286. content = f'{content}<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1287. else:
  1288. if raw:
  1289. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1290. else:
  1291. content = f'{content}<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1292. else:
  1293. block_content = str(block["content"]).strip()
  1294. if block_content:
  1295. content = f"{content}{block['type']}: {block_content}\n"
  1296. return content.strip()
  1297. def convert_content_blocks_to_messages(content_blocks, raw=False):
  1298. messages = []
  1299. temp_blocks = []
  1300. for idx, block in enumerate(content_blocks):
  1301. if block["type"] == "tool_calls":
  1302. messages.append(
  1303. {
  1304. "role": "assistant",
  1305. "content": serialize_content_blocks(temp_blocks, raw),
  1306. "tool_calls": block.get("content"),
  1307. }
  1308. )
  1309. results = block.get("results", [])
  1310. for result in results:
  1311. messages.append(
  1312. {
  1313. "role": "tool",
  1314. "tool_call_id": result["tool_call_id"],
  1315. "content": result["content"],
  1316. }
  1317. )
  1318. temp_blocks = []
  1319. else:
  1320. temp_blocks.append(block)
  1321. if temp_blocks:
  1322. content = serialize_content_blocks(temp_blocks, raw)
  1323. if content:
  1324. messages.append(
  1325. {
  1326. "role": "assistant",
  1327. "content": content,
  1328. }
  1329. )
  1330. return messages
  1331. def tag_content_handler(content_type, tags, content, content_blocks):
  1332. end_flag = False
  1333. def extract_attributes(tag_content):
  1334. """Extract attributes from a tag if they exist."""
  1335. attributes = {}
  1336. if not tag_content: # Ensure tag_content is not None
  1337. return attributes
  1338. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1339. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1340. for key, value in matches:
  1341. attributes[key] = value
  1342. return attributes
  1343. if content_blocks[-1]["type"] == "text":
  1344. for start_tag, end_tag in tags:
  1345. start_tag_pattern = rf"{re.escape(start_tag)}"
  1346. if start_tag.startswith("<") and start_tag.endswith(">"):
  1347. # Match start tag e.g., <tag> or <tag attr="value">
  1348. # remove both '<' and '>' from start_tag
  1349. # Match start tag with attributes
  1350. start_tag_pattern = (
  1351. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1352. )
  1353. match = re.search(start_tag_pattern, content)
  1354. if match:
  1355. attr_content = (
  1356. match.group(1) if match.group(1) else ""
  1357. ) # Ensure it's not None
  1358. attributes = extract_attributes(
  1359. attr_content
  1360. ) # Extract attributes safely
  1361. # Capture everything before and after the matched tag
  1362. before_tag = content[
  1363. : match.start()
  1364. ] # Content before opening tag
  1365. after_tag = content[
  1366. match.end() :
  1367. ] # Content after opening tag
  1368. # Remove the start tag and after from the currently handling text block
  1369. content_blocks[-1]["content"] = content_blocks[-1][
  1370. "content"
  1371. ].replace(match.group(0) + after_tag, "")
  1372. if before_tag:
  1373. content_blocks[-1]["content"] = before_tag
  1374. if not content_blocks[-1]["content"]:
  1375. content_blocks.pop()
  1376. # Append the new block
  1377. content_blocks.append(
  1378. {
  1379. "type": content_type,
  1380. "start_tag": start_tag,
  1381. "end_tag": end_tag,
  1382. "attributes": attributes,
  1383. "content": "",
  1384. "started_at": time.time(),
  1385. }
  1386. )
  1387. if after_tag:
  1388. content_blocks[-1]["content"] = after_tag
  1389. tag_content_handler(
  1390. content_type, tags, after_tag, content_blocks
  1391. )
  1392. break
  1393. elif content_blocks[-1]["type"] == content_type:
  1394. start_tag = content_blocks[-1]["start_tag"]
  1395. end_tag = content_blocks[-1]["end_tag"]
  1396. if end_tag.startswith("<") and end_tag.endswith(">"):
  1397. # Match end tag e.g., </tag>
  1398. end_tag_pattern = rf"{re.escape(end_tag)}"
  1399. else:
  1400. # Handle cases where end_tag is just a tag name
  1401. end_tag_pattern = rf"{re.escape(end_tag)}"
  1402. # Check if the content has the end tag
  1403. if re.search(end_tag_pattern, content):
  1404. end_flag = True
  1405. block_content = content_blocks[-1]["content"]
  1406. # Strip start and end tags from the content
  1407. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1408. block_content = re.sub(
  1409. start_tag_pattern, "", block_content
  1410. ).strip()
  1411. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1412. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1413. # Content inside the tag
  1414. block_content = (
  1415. split_content[0].strip() if split_content else ""
  1416. )
  1417. # Leftover content (everything after `</tag>`)
  1418. leftover_content = (
  1419. split_content[1].strip() if len(split_content) > 1 else ""
  1420. )
  1421. if block_content:
  1422. content_blocks[-1]["content"] = block_content
  1423. content_blocks[-1]["ended_at"] = time.time()
  1424. content_blocks[-1]["duration"] = int(
  1425. content_blocks[-1]["ended_at"]
  1426. - content_blocks[-1]["started_at"]
  1427. )
  1428. # Reset the content_blocks by appending a new text block
  1429. if content_type != "code_interpreter":
  1430. if leftover_content:
  1431. content_blocks.append(
  1432. {
  1433. "type": "text",
  1434. "content": leftover_content,
  1435. }
  1436. )
  1437. else:
  1438. content_blocks.append(
  1439. {
  1440. "type": "text",
  1441. "content": "",
  1442. }
  1443. )
  1444. else:
  1445. # Remove the block if content is empty
  1446. content_blocks.pop()
  1447. if leftover_content:
  1448. content_blocks.append(
  1449. {
  1450. "type": "text",
  1451. "content": leftover_content,
  1452. }
  1453. )
  1454. else:
  1455. content_blocks.append(
  1456. {
  1457. "type": "text",
  1458. "content": "",
  1459. }
  1460. )
  1461. # Clean processed content
  1462. start_tag_pattern = rf"{re.escape(start_tag)}"
  1463. if start_tag.startswith("<") and start_tag.endswith(">"):
  1464. # Match start tag e.g., <tag> or <tag attr="value">
  1465. # remove both '<' and '>' from start_tag
  1466. # Match start tag with attributes
  1467. start_tag_pattern = (
  1468. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1469. )
  1470. content = re.sub(
  1471. rf"{start_tag_pattern}(.|\n)*?{re.escape(end_tag)}",
  1472. "",
  1473. content,
  1474. flags=re.DOTALL,
  1475. )
  1476. return content, content_blocks, end_flag
  1477. message = Chats.get_message_by_id_and_message_id(
  1478. metadata["chat_id"], metadata["message_id"]
  1479. )
  1480. tool_calls = []
  1481. last_assistant_message = None
  1482. try:
  1483. if form_data["messages"][-1]["role"] == "assistant":
  1484. last_assistant_message = get_last_assistant_message(
  1485. form_data["messages"]
  1486. )
  1487. except Exception as e:
  1488. pass
  1489. content = (
  1490. message.get("content", "")
  1491. if message
  1492. else last_assistant_message if last_assistant_message else ""
  1493. )
  1494. content_blocks = [
  1495. {
  1496. "type": "text",
  1497. "content": content,
  1498. }
  1499. ]
  1500. # We might want to disable this by default
  1501. DETECT_REASONING = True
  1502. DETECT_SOLUTION = True
  1503. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1504. "code_interpreter", False
  1505. )
  1506. reasoning_tags = [
  1507. ("<think>", "</think>"),
  1508. ("<thinking>", "</thinking>"),
  1509. ("<reason>", "</reason>"),
  1510. ("<reasoning>", "</reasoning>"),
  1511. ("<thought>", "</thought>"),
  1512. ("<Thought>", "</Thought>"),
  1513. ("<|begin_of_thought|>", "<|end_of_thought|>"),
  1514. ("◁think▷", "◁/think▷"),
  1515. ]
  1516. code_interpreter_tags = [("<code_interpreter>", "</code_interpreter>")]
  1517. solution_tags = [("<|begin_of_solution|>", "<|end_of_solution|>")]
  1518. try:
  1519. for event in events:
  1520. await event_emitter(
  1521. {
  1522. "type": "chat:completion",
  1523. "data": event,
  1524. }
  1525. )
  1526. # Save message in the database
  1527. Chats.upsert_message_to_chat_by_id_and_message_id(
  1528. metadata["chat_id"],
  1529. metadata["message_id"],
  1530. {
  1531. **event,
  1532. },
  1533. )
  1534. async def stream_body_handler(response, form_data):
  1535. nonlocal content
  1536. nonlocal content_blocks
  1537. response_tool_calls = []
  1538. async for line in response.body_iterator:
  1539. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1540. data = line
  1541. # Skip empty lines
  1542. if not data.strip():
  1543. continue
  1544. # "data:" is the prefix for each event
  1545. if not data.startswith("data:"):
  1546. continue
  1547. # Remove the prefix
  1548. data = data[len("data:") :].strip()
  1549. try:
  1550. data = json.loads(data)
  1551. data, _ = await process_filter_functions(
  1552. request=request,
  1553. filter_functions=filter_functions,
  1554. filter_type="stream",
  1555. form_data=data,
  1556. extra_params={"__body__": form_data, **extra_params},
  1557. )
  1558. if data:
  1559. if "event" in data:
  1560. await event_emitter(data.get("event", {}))
  1561. if "selected_model_id" in data:
  1562. model_id = data["selected_model_id"]
  1563. Chats.upsert_message_to_chat_by_id_and_message_id(
  1564. metadata["chat_id"],
  1565. metadata["message_id"],
  1566. {
  1567. "selectedModelId": model_id,
  1568. },
  1569. )
  1570. else:
  1571. choices = data.get("choices", [])
  1572. if not choices:
  1573. error = data.get("error", {})
  1574. if error:
  1575. await event_emitter(
  1576. {
  1577. "type": "chat:completion",
  1578. "data": {
  1579. "error": error,
  1580. },
  1581. }
  1582. )
  1583. usage = data.get("usage", {})
  1584. if usage:
  1585. await event_emitter(
  1586. {
  1587. "type": "chat:completion",
  1588. "data": {
  1589. "usage": usage,
  1590. },
  1591. }
  1592. )
  1593. continue
  1594. delta = choices[0].get("delta", {})
  1595. delta_tool_calls = delta.get("tool_calls", None)
  1596. if delta_tool_calls:
  1597. for delta_tool_call in delta_tool_calls:
  1598. tool_call_index = delta_tool_call.get(
  1599. "index"
  1600. )
  1601. if tool_call_index is not None:
  1602. # Check if the tool call already exists
  1603. current_response_tool_call = None
  1604. for (
  1605. response_tool_call
  1606. ) in response_tool_calls:
  1607. if (
  1608. response_tool_call.get("index")
  1609. == tool_call_index
  1610. ):
  1611. current_response_tool_call = (
  1612. response_tool_call
  1613. )
  1614. break
  1615. if current_response_tool_call is None:
  1616. # Add the new tool call
  1617. delta_tool_call.setdefault(
  1618. "function", {}
  1619. )
  1620. delta_tool_call[
  1621. "function"
  1622. ].setdefault("name", "")
  1623. delta_tool_call[
  1624. "function"
  1625. ].setdefault("arguments", "")
  1626. response_tool_calls.append(
  1627. delta_tool_call
  1628. )
  1629. else:
  1630. # Update the existing tool call
  1631. delta_name = delta_tool_call.get(
  1632. "function", {}
  1633. ).get("name")
  1634. delta_arguments = (
  1635. delta_tool_call.get(
  1636. "function", {}
  1637. ).get("arguments")
  1638. )
  1639. if delta_name:
  1640. current_response_tool_call[
  1641. "function"
  1642. ]["name"] += delta_name
  1643. if delta_arguments:
  1644. current_response_tool_call[
  1645. "function"
  1646. ][
  1647. "arguments"
  1648. ] += delta_arguments
  1649. value = delta.get("content")
  1650. reasoning_content = (
  1651. delta.get("reasoning_content")
  1652. or delta.get("reasoning")
  1653. or delta.get("thinking")
  1654. )
  1655. if reasoning_content:
  1656. if (
  1657. not content_blocks
  1658. or content_blocks[-1]["type"] != "reasoning"
  1659. ):
  1660. reasoning_block = {
  1661. "type": "reasoning",
  1662. "start_tag": "<think>",
  1663. "end_tag": "</think>",
  1664. "attributes": {
  1665. "type": "reasoning_content"
  1666. },
  1667. "content": "",
  1668. "started_at": time.time(),
  1669. }
  1670. content_blocks.append(reasoning_block)
  1671. else:
  1672. reasoning_block = content_blocks[-1]
  1673. reasoning_block["content"] += reasoning_content
  1674. data = {
  1675. "content": serialize_content_blocks(
  1676. content_blocks
  1677. )
  1678. }
  1679. if value:
  1680. if (
  1681. content_blocks
  1682. and content_blocks[-1]["type"]
  1683. == "reasoning"
  1684. and content_blocks[-1]
  1685. .get("attributes", {})
  1686. .get("type")
  1687. == "reasoning_content"
  1688. ):
  1689. reasoning_block = content_blocks[-1]
  1690. reasoning_block["ended_at"] = time.time()
  1691. reasoning_block["duration"] = int(
  1692. reasoning_block["ended_at"]
  1693. - reasoning_block["started_at"]
  1694. )
  1695. content_blocks.append(
  1696. {
  1697. "type": "text",
  1698. "content": "",
  1699. }
  1700. )
  1701. content = f"{content}{value}"
  1702. if not content_blocks:
  1703. content_blocks.append(
  1704. {
  1705. "type": "text",
  1706. "content": "",
  1707. }
  1708. )
  1709. content_blocks[-1]["content"] = (
  1710. content_blocks[-1]["content"] + value
  1711. )
  1712. if DETECT_REASONING:
  1713. content, content_blocks, _ = (
  1714. tag_content_handler(
  1715. "reasoning",
  1716. reasoning_tags,
  1717. content,
  1718. content_blocks,
  1719. )
  1720. )
  1721. if DETECT_CODE_INTERPRETER:
  1722. content, content_blocks, end = (
  1723. tag_content_handler(
  1724. "code_interpreter",
  1725. code_interpreter_tags,
  1726. content,
  1727. content_blocks,
  1728. )
  1729. )
  1730. if end:
  1731. break
  1732. if DETECT_SOLUTION:
  1733. content, content_blocks, _ = (
  1734. tag_content_handler(
  1735. "solution",
  1736. solution_tags,
  1737. content,
  1738. content_blocks,
  1739. )
  1740. )
  1741. if ENABLE_REALTIME_CHAT_SAVE:
  1742. # Save message in the database
  1743. Chats.upsert_message_to_chat_by_id_and_message_id(
  1744. metadata["chat_id"],
  1745. metadata["message_id"],
  1746. {
  1747. "content": serialize_content_blocks(
  1748. content_blocks
  1749. ),
  1750. },
  1751. )
  1752. else:
  1753. data = {
  1754. "content": serialize_content_blocks(
  1755. content_blocks
  1756. ),
  1757. }
  1758. await event_emitter(
  1759. {
  1760. "type": "chat:completion",
  1761. "data": data,
  1762. }
  1763. )
  1764. except Exception as e:
  1765. done = "data: [DONE]" in line
  1766. if done:
  1767. pass
  1768. else:
  1769. log.debug(f"Error: {e}")
  1770. continue
  1771. if content_blocks:
  1772. # Clean up the last text block
  1773. if content_blocks[-1]["type"] == "text":
  1774. content_blocks[-1]["content"] = content_blocks[-1][
  1775. "content"
  1776. ].strip()
  1777. if not content_blocks[-1]["content"]:
  1778. content_blocks.pop()
  1779. if not content_blocks:
  1780. content_blocks.append(
  1781. {
  1782. "type": "text",
  1783. "content": "",
  1784. }
  1785. )
  1786. if content_blocks[-1]["type"] == "reasoning":
  1787. reasoning_block = content_blocks[-1]
  1788. if reasoning_block.get("ended_at") is None:
  1789. reasoning_block["ended_at"] = time.time()
  1790. reasoning_block["duration"] = int(
  1791. reasoning_block["ended_at"]
  1792. - reasoning_block["started_at"]
  1793. )
  1794. if response_tool_calls:
  1795. tool_calls.append(response_tool_calls)
  1796. if response.background:
  1797. await response.background()
  1798. await stream_body_handler(response, form_data)
  1799. MAX_TOOL_CALL_RETRIES = 10
  1800. tool_call_retries = 0
  1801. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1802. tool_call_retries += 1
  1803. response_tool_calls = tool_calls.pop(0)
  1804. content_blocks.append(
  1805. {
  1806. "type": "tool_calls",
  1807. "content": response_tool_calls,
  1808. }
  1809. )
  1810. await event_emitter(
  1811. {
  1812. "type": "chat:completion",
  1813. "data": {
  1814. "content": serialize_content_blocks(content_blocks),
  1815. },
  1816. }
  1817. )
  1818. tools = metadata.get("tools", {})
  1819. results = []
  1820. for tool_call in response_tool_calls:
  1821. tool_call_id = tool_call.get("id", "")
  1822. tool_name = tool_call.get("function", {}).get("name", "")
  1823. tool_args = tool_call.get("function", {}).get("arguments", "{}")
  1824. tool_function_params = {}
  1825. try:
  1826. # json.loads cannot be used because some models do not produce valid JSON
  1827. tool_function_params = ast.literal_eval(tool_args)
  1828. except Exception as e:
  1829. log.debug(e)
  1830. # Fallback to JSON parsing
  1831. try:
  1832. tool_function_params = json.loads(tool_args)
  1833. except Exception as e:
  1834. log.error(
  1835. f"Error parsing tool call arguments: {tool_args}"
  1836. )
  1837. # Mutate the original tool call response params as they are passed back to the passed
  1838. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  1839. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  1840. # params are not valid json.
  1841. # Main case so far is no args = "" = invalid json.
  1842. log.debug(
  1843. f"Parsed args from {tool_args} to {tool_function_params}"
  1844. )
  1845. tool_call.setdefault("function", {})["arguments"] = json.dumps(
  1846. tool_function_params
  1847. )
  1848. tool_result = None
  1849. if tool_name in tools:
  1850. tool = tools[tool_name]
  1851. spec = tool.get("spec", {})
  1852. try:
  1853. allowed_params = (
  1854. spec.get("parameters", {})
  1855. .get("properties", {})
  1856. .keys()
  1857. )
  1858. tool_function_params = {
  1859. k: v
  1860. for k, v in tool_function_params.items()
  1861. if k in allowed_params
  1862. }
  1863. if tool.get("direct", False):
  1864. tool_result = await event_caller(
  1865. {
  1866. "type": "execute:tool",
  1867. "data": {
  1868. "id": str(uuid4()),
  1869. "name": tool_name,
  1870. "params": tool_function_params,
  1871. "server": tool.get("server", {}),
  1872. "session_id": metadata.get(
  1873. "session_id", None
  1874. ),
  1875. },
  1876. }
  1877. )
  1878. else:
  1879. tool_function = tool["callable"]
  1880. tool_result = await tool_function(
  1881. **tool_function_params
  1882. )
  1883. except Exception as e:
  1884. tool_result = str(e)
  1885. tool_result_files = []
  1886. if isinstance(tool_result, list):
  1887. for item in tool_result:
  1888. # check if string
  1889. if isinstance(item, str) and item.startswith("data:"):
  1890. tool_result_files.append(item)
  1891. tool_result.remove(item)
  1892. if isinstance(tool_result, dict) or isinstance(
  1893. tool_result, list
  1894. ):
  1895. tool_result = json.dumps(
  1896. tool_result, indent=2, ensure_ascii=False
  1897. )
  1898. results.append(
  1899. {
  1900. "tool_call_id": tool_call_id,
  1901. "content": tool_result,
  1902. **(
  1903. {"files": tool_result_files}
  1904. if tool_result_files
  1905. else {}
  1906. ),
  1907. }
  1908. )
  1909. content_blocks[-1]["results"] = results
  1910. content_blocks.append(
  1911. {
  1912. "type": "text",
  1913. "content": "",
  1914. }
  1915. )
  1916. await event_emitter(
  1917. {
  1918. "type": "chat:completion",
  1919. "data": {
  1920. "content": serialize_content_blocks(content_blocks),
  1921. },
  1922. }
  1923. )
  1924. try:
  1925. new_form_data = {
  1926. "model": model_id,
  1927. "stream": True,
  1928. "tools": form_data["tools"],
  1929. "messages": [
  1930. *form_data["messages"],
  1931. *convert_content_blocks_to_messages(
  1932. content_blocks, True
  1933. ),
  1934. ],
  1935. }
  1936. res = await generate_chat_completion(
  1937. request,
  1938. new_form_data,
  1939. user,
  1940. )
  1941. if isinstance(res, StreamingResponse):
  1942. await stream_body_handler(res, new_form_data)
  1943. else:
  1944. break
  1945. except Exception as e:
  1946. log.debug(e)
  1947. break
  1948. if DETECT_CODE_INTERPRETER:
  1949. MAX_RETRIES = 5
  1950. retries = 0
  1951. while (
  1952. content_blocks[-1]["type"] == "code_interpreter"
  1953. and retries < MAX_RETRIES
  1954. ):
  1955. await event_emitter(
  1956. {
  1957. "type": "chat:completion",
  1958. "data": {
  1959. "content": serialize_content_blocks(content_blocks),
  1960. },
  1961. }
  1962. )
  1963. retries += 1
  1964. log.debug(f"Attempt count: {retries}")
  1965. output = ""
  1966. try:
  1967. if content_blocks[-1]["attributes"].get("type") == "code":
  1968. code = content_blocks[-1]["content"]
  1969. if (
  1970. request.app.state.config.CODE_INTERPRETER_ENGINE
  1971. == "pyodide"
  1972. ):
  1973. output = await event_caller(
  1974. {
  1975. "type": "execute:python",
  1976. "data": {
  1977. "id": str(uuid4()),
  1978. "code": code,
  1979. "session_id": metadata.get(
  1980. "session_id", None
  1981. ),
  1982. },
  1983. }
  1984. )
  1985. elif (
  1986. request.app.state.config.CODE_INTERPRETER_ENGINE
  1987. == "jupyter"
  1988. ):
  1989. output = await execute_code_jupyter(
  1990. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  1991. code,
  1992. (
  1993. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  1994. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1995. == "token"
  1996. else None
  1997. ),
  1998. (
  1999. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  2000. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2001. == "password"
  2002. else None
  2003. ),
  2004. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  2005. )
  2006. else:
  2007. output = {
  2008. "stdout": "Code interpreter engine not configured."
  2009. }
  2010. log.debug(f"Code interpreter output: {output}")
  2011. if isinstance(output, dict):
  2012. stdout = output.get("stdout", "")
  2013. if isinstance(stdout, str):
  2014. stdoutLines = stdout.split("\n")
  2015. for idx, line in enumerate(stdoutLines):
  2016. if "data:image/png;base64" in line:
  2017. image_url = ""
  2018. # Extract base64 image data from the line
  2019. image_data, content_type = (
  2020. load_b64_image_data(line)
  2021. )
  2022. if image_data is not None:
  2023. image_url = upload_image(
  2024. request,
  2025. image_data,
  2026. content_type,
  2027. metadata,
  2028. user,
  2029. )
  2030. stdoutLines[idx] = (
  2031. f"![Output Image]({image_url})"
  2032. )
  2033. output["stdout"] = "\n".join(stdoutLines)
  2034. result = output.get("result", "")
  2035. if isinstance(result, str):
  2036. resultLines = result.split("\n")
  2037. for idx, line in enumerate(resultLines):
  2038. if "data:image/png;base64" in line:
  2039. image_url = ""
  2040. # Extract base64 image data from the line
  2041. image_data, content_type = (
  2042. load_b64_image_data(line)
  2043. )
  2044. if image_data is not None:
  2045. image_url = upload_image(
  2046. request,
  2047. image_data,
  2048. content_type,
  2049. metadata,
  2050. user,
  2051. )
  2052. resultLines[idx] = (
  2053. f"![Output Image]({image_url})"
  2054. )
  2055. output["result"] = "\n".join(resultLines)
  2056. except Exception as e:
  2057. output = str(e)
  2058. content_blocks[-1]["output"] = output
  2059. content_blocks.append(
  2060. {
  2061. "type": "text",
  2062. "content": "",
  2063. }
  2064. )
  2065. await event_emitter(
  2066. {
  2067. "type": "chat:completion",
  2068. "data": {
  2069. "content": serialize_content_blocks(content_blocks),
  2070. },
  2071. }
  2072. )
  2073. try:
  2074. new_form_data = {
  2075. "model": model_id,
  2076. "stream": True,
  2077. "messages": [
  2078. *form_data["messages"],
  2079. {
  2080. "role": "assistant",
  2081. "content": serialize_content_blocks(
  2082. content_blocks, raw=True
  2083. ),
  2084. },
  2085. ],
  2086. }
  2087. res = await generate_chat_completion(
  2088. request,
  2089. new_form_data,
  2090. user,
  2091. )
  2092. if isinstance(res, StreamingResponse):
  2093. await stream_body_handler(res, new_form_data)
  2094. else:
  2095. break
  2096. except Exception as e:
  2097. log.debug(e)
  2098. break
  2099. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  2100. data = {
  2101. "done": True,
  2102. "content": serialize_content_blocks(content_blocks),
  2103. "title": title,
  2104. }
  2105. if not ENABLE_REALTIME_CHAT_SAVE:
  2106. # Save message in the database
  2107. Chats.upsert_message_to_chat_by_id_and_message_id(
  2108. metadata["chat_id"],
  2109. metadata["message_id"],
  2110. {
  2111. "content": serialize_content_blocks(content_blocks),
  2112. },
  2113. )
  2114. # Send a webhook notification if the user is not active
  2115. if not get_active_status_by_user_id(user.id):
  2116. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  2117. if webhook_url:
  2118. post_webhook(
  2119. request.app.state.WEBUI_NAME,
  2120. webhook_url,
  2121. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  2122. {
  2123. "action": "chat",
  2124. "message": content,
  2125. "title": title,
  2126. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  2127. },
  2128. )
  2129. await event_emitter(
  2130. {
  2131. "type": "chat:completion",
  2132. "data": data,
  2133. }
  2134. )
  2135. await background_tasks_handler()
  2136. except asyncio.CancelledError:
  2137. log.warning("Task was cancelled!")
  2138. await event_emitter({"type": "task-cancelled"})
  2139. if not ENABLE_REALTIME_CHAT_SAVE:
  2140. # Save message in the database
  2141. Chats.upsert_message_to_chat_by_id_and_message_id(
  2142. metadata["chat_id"],
  2143. metadata["message_id"],
  2144. {
  2145. "content": serialize_content_blocks(content_blocks),
  2146. },
  2147. )
  2148. if response.background is not None:
  2149. await response.background()
  2150. # background_tasks.add_task(response_handler, response, events)
  2151. task_id, _ = await create_task(
  2152. request.app.state.redis,
  2153. response_handler(response, events),
  2154. id=metadata["chat_id"],
  2155. )
  2156. return {"status": True, "task_id": task_id}
  2157. else:
  2158. # Fallback to the original response
  2159. async def stream_wrapper(original_generator, events):
  2160. def wrap_item(item):
  2161. return f"data: {item}\n\n"
  2162. for event in events:
  2163. event, _ = await process_filter_functions(
  2164. request=request,
  2165. filter_functions=filter_functions,
  2166. filter_type="stream",
  2167. form_data=event,
  2168. extra_params=extra_params,
  2169. )
  2170. if event:
  2171. yield wrap_item(json.dumps(event))
  2172. async for data in original_generator:
  2173. data, _ = await process_filter_functions(
  2174. request=request,
  2175. filter_functions=filter_functions,
  2176. filter_type="stream",
  2177. form_data=data,
  2178. extra_params=extra_params,
  2179. )
  2180. if data:
  2181. yield data
  2182. return StreamingResponse(
  2183. stream_wrapper(response.body_iterator, events),
  2184. headers=dict(response.headers),
  2185. background=response.background,
  2186. )