1
0

middleware.py 109 KB

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