middleware.py 108 KB

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