middleware.py 111 KB

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