middleware.py 107 KB

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