middleware.py 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188
  1. import time
  2. import logging
  3. import sys
  4. import os
  5. import base64
  6. import asyncio
  7. from aiocache import cached
  8. from typing import Any, Optional
  9. import random
  10. import json
  11. import html
  12. import inspect
  13. import re
  14. import ast
  15. from uuid import uuid4
  16. from concurrent.futures import ThreadPoolExecutor
  17. from fastapi import Request
  18. from fastapi import BackgroundTasks
  19. from starlette.responses import Response, StreamingResponse
  20. from open_webui.models.chats import Chats
  21. from open_webui.models.users import Users
  22. from open_webui.socket.main import (
  23. get_event_call,
  24. get_event_emitter,
  25. get_active_status_by_user_id,
  26. )
  27. from open_webui.routers.tasks import (
  28. generate_queries,
  29. generate_title,
  30. generate_image_prompt,
  31. generate_chat_tags,
  32. )
  33. from open_webui.routers.retrieval import process_web_search, SearchForm
  34. from open_webui.routers.images import image_generations, GenerateImageForm
  35. from open_webui.routers.pipelines import (
  36. process_pipeline_inlet_filter,
  37. process_pipeline_outlet_filter,
  38. )
  39. from open_webui.utils.webhook import post_webhook
  40. from open_webui.models.users import UserModel
  41. from open_webui.models.functions import Functions
  42. from open_webui.models.models import Models
  43. from open_webui.retrieval.utils import get_sources_from_files
  44. from open_webui.utils.chat import generate_chat_completion
  45. from open_webui.utils.task import (
  46. get_task_model_id,
  47. rag_template,
  48. tools_function_calling_generation_template,
  49. )
  50. from open_webui.utils.misc import (
  51. deep_update,
  52. get_message_list,
  53. add_or_update_system_message,
  54. add_or_update_user_message,
  55. get_last_user_message,
  56. get_last_assistant_message,
  57. prepend_to_first_user_message_content,
  58. convert_logit_bias_input_to_json,
  59. )
  60. from open_webui.utils.tools import get_tools
  61. from open_webui.utils.plugin import load_function_module_by_id
  62. from open_webui.utils.filter import (
  63. get_sorted_filter_ids,
  64. process_filter_functions,
  65. )
  66. from open_webui.utils.code_interpreter import execute_code_jupyter
  67. from open_webui.tasks import create_task
  68. from open_webui.config import (
  69. CACHE_DIR,
  70. DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  71. DEFAULT_CODE_INTERPRETER_PROMPT,
  72. )
  73. from open_webui.env import (
  74. SRC_LOG_LEVELS,
  75. GLOBAL_LOG_LEVEL,
  76. BYPASS_MODEL_ACCESS_CONTROL,
  77. ENABLE_REALTIME_CHAT_SAVE,
  78. )
  79. from open_webui.constants import TASKS
  80. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  81. log = logging.getLogger(__name__)
  82. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  83. async def chat_completion_tools_handler(
  84. request: Request, body: dict, extra_params: dict, user: UserModel, models, tools
  85. ) -> tuple[dict, dict]:
  86. async def get_content_from_response(response) -> Optional[str]:
  87. content = None
  88. if hasattr(response, "body_iterator"):
  89. async for chunk in response.body_iterator:
  90. data = json.loads(chunk.decode("utf-8"))
  91. content = data["choices"][0]["message"]["content"]
  92. # Cleanup any remaining background tasks if necessary
  93. if response.background is not None:
  94. await response.background()
  95. else:
  96. content = response["choices"][0]["message"]["content"]
  97. return content
  98. def get_tools_function_calling_payload(messages, task_model_id, content):
  99. user_message = get_last_user_message(messages)
  100. history = "\n".join(
  101. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  102. for message in messages[::-1][:4]
  103. )
  104. prompt = f"History:\n{history}\nQuery: {user_message}"
  105. return {
  106. "model": task_model_id,
  107. "messages": [
  108. {"role": "system", "content": content},
  109. {"role": "user", "content": f"Query: {prompt}"},
  110. ],
  111. "stream": False,
  112. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  113. }
  114. event_caller = extra_params["__event_call__"]
  115. metadata = extra_params["__metadata__"]
  116. task_model_id = get_task_model_id(
  117. body["model"],
  118. request.app.state.config.TASK_MODEL,
  119. request.app.state.config.TASK_MODEL_EXTERNAL,
  120. models,
  121. )
  122. skip_files = False
  123. sources = []
  124. specs = [tool["spec"] for tool in tools.values()]
  125. tools_specs = json.dumps(specs)
  126. if request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  127. template = request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  128. else:
  129. template = DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  130. tools_function_calling_prompt = tools_function_calling_generation_template(
  131. template, tools_specs
  132. )
  133. log.info(f"{tools_function_calling_prompt=}")
  134. payload = get_tools_function_calling_payload(
  135. body["messages"], task_model_id, tools_function_calling_prompt
  136. )
  137. try:
  138. response = await generate_chat_completion(request, form_data=payload, user=user)
  139. log.debug(f"{response=}")
  140. content = await get_content_from_response(response)
  141. log.debug(f"{content=}")
  142. if not content:
  143. return body, {}
  144. try:
  145. content = content[content.find("{") : content.rfind("}") + 1]
  146. if not content:
  147. raise Exception("No JSON object found in the response")
  148. result = json.loads(content)
  149. async def tool_call_handler(tool_call):
  150. nonlocal skip_files
  151. log.debug(f"{tool_call=}")
  152. tool_function_name = tool_call.get("name", None)
  153. if tool_function_name not in tools:
  154. return body, {}
  155. tool_function_params = tool_call.get("parameters", {})
  156. try:
  157. tool = tools[tool_function_name]
  158. spec = tool.get("spec", {})
  159. allowed_params = (
  160. spec.get("parameters", {}).get("properties", {}).keys()
  161. )
  162. tool_function = tool["callable"]
  163. tool_function_params = {
  164. k: v
  165. for k, v in tool_function_params.items()
  166. if k in allowed_params
  167. }
  168. if tool.get("direct", False):
  169. tool_output = await tool_function(**tool_function_params)
  170. else:
  171. tool_output = await event_caller(
  172. {
  173. "type": "execute:tool",
  174. "data": {
  175. "id": str(uuid4()),
  176. "name": tool_function_name,
  177. "params": tool_function_params,
  178. "tool": tool,
  179. "server": tool.get("server", {}),
  180. "session_id": metadata.get("session_id", None),
  181. },
  182. }
  183. )
  184. except Exception as e:
  185. tool_output = str(e)
  186. if isinstance(tool_output, dict):
  187. tool_output = json.dumps(tool_output, indent=4)
  188. if isinstance(tool_output, str):
  189. tool_id = tools[tool_function_name].get("toolkit_id", "")
  190. if tools[tool_function_name].get("citation", False):
  191. sources.append(
  192. {
  193. "source": {
  194. "name": (
  195. f"TOOL:" + f"{tool_id}/{tool_function_name}"
  196. if tool_id
  197. else f"{tool_function_name}"
  198. ),
  199. },
  200. "document": [tool_output],
  201. "metadata": [
  202. {
  203. "source": (
  204. f"TOOL:" + f"{tool_id}/{tool_function_name}"
  205. if tool_id
  206. else f"{tool_function_name}"
  207. )
  208. }
  209. ],
  210. }
  211. )
  212. else:
  213. sources.append(
  214. {
  215. "source": {},
  216. "document": [tool_output],
  217. "metadata": [
  218. {
  219. "source": (
  220. f"TOOL:" + f"{tool_id}/{tool_function_name}"
  221. if tool_id
  222. else f"{tool_function_name}"
  223. )
  224. }
  225. ],
  226. }
  227. )
  228. if tools[tool_function_name].get("file_handler", False):
  229. skip_files = True
  230. # check if "tool_calls" in result
  231. if result.get("tool_calls"):
  232. for tool_call in result.get("tool_calls"):
  233. await tool_call_handler(tool_call)
  234. else:
  235. await tool_call_handler(result)
  236. except Exception as e:
  237. log.exception(f"Error: {e}")
  238. content = None
  239. except Exception as e:
  240. log.exception(f"Error: {e}")
  241. content = None
  242. log.debug(f"tool_contexts: {sources}")
  243. if skip_files and "files" in body.get("metadata", {}):
  244. del body["metadata"]["files"]
  245. return body, {"sources": sources}
  246. async def chat_web_search_handler(
  247. request: Request, form_data: dict, extra_params: dict, user
  248. ):
  249. event_emitter = extra_params["__event_emitter__"]
  250. await event_emitter(
  251. {
  252. "type": "status",
  253. "data": {
  254. "action": "web_search",
  255. "description": "Generating search query",
  256. "done": False,
  257. },
  258. }
  259. )
  260. messages = form_data["messages"]
  261. user_message = get_last_user_message(messages)
  262. queries = []
  263. try:
  264. res = await generate_queries(
  265. request,
  266. {
  267. "model": form_data["model"],
  268. "messages": messages,
  269. "prompt": user_message,
  270. "type": "web_search",
  271. },
  272. user,
  273. )
  274. response = res["choices"][0]["message"]["content"]
  275. try:
  276. bracket_start = response.find("{")
  277. bracket_end = response.rfind("}") + 1
  278. if bracket_start == -1 or bracket_end == -1:
  279. raise Exception("No JSON object found in the response")
  280. response = response[bracket_start:bracket_end]
  281. queries = json.loads(response)
  282. queries = queries.get("queries", [])
  283. except Exception as e:
  284. queries = [response]
  285. except Exception as e:
  286. log.exception(e)
  287. queries = [user_message]
  288. if len(queries) == 0:
  289. await event_emitter(
  290. {
  291. "type": "status",
  292. "data": {
  293. "action": "web_search",
  294. "description": "No search query generated",
  295. "done": True,
  296. },
  297. }
  298. )
  299. return form_data
  300. all_results = []
  301. for searchQuery in queries:
  302. await event_emitter(
  303. {
  304. "type": "status",
  305. "data": {
  306. "action": "web_search",
  307. "description": 'Searching "{{searchQuery}}"',
  308. "query": searchQuery,
  309. "done": False,
  310. },
  311. }
  312. )
  313. try:
  314. results = await process_web_search(
  315. request,
  316. SearchForm(
  317. **{
  318. "query": searchQuery,
  319. }
  320. ),
  321. user=user,
  322. )
  323. if results:
  324. all_results.append(results)
  325. files = form_data.get("files", [])
  326. if results.get("collection_name"):
  327. files.append(
  328. {
  329. "collection_name": results["collection_name"],
  330. "name": searchQuery,
  331. "type": "web_search",
  332. "urls": results["filenames"],
  333. }
  334. )
  335. elif results.get("docs"):
  336. files.append(
  337. {
  338. "docs": results.get("docs", []),
  339. "name": searchQuery,
  340. "type": "web_search",
  341. "urls": results["filenames"],
  342. }
  343. )
  344. form_data["files"] = files
  345. except Exception as e:
  346. log.exception(e)
  347. await event_emitter(
  348. {
  349. "type": "status",
  350. "data": {
  351. "action": "web_search",
  352. "description": 'Error searching "{{searchQuery}}"',
  353. "query": searchQuery,
  354. "done": True,
  355. "error": True,
  356. },
  357. }
  358. )
  359. if all_results:
  360. urls = []
  361. for results in all_results:
  362. if "filenames" in results:
  363. urls.extend(results["filenames"])
  364. await event_emitter(
  365. {
  366. "type": "status",
  367. "data": {
  368. "action": "web_search",
  369. "description": "Searched {{count}} sites",
  370. "urls": urls,
  371. "done": True,
  372. },
  373. }
  374. )
  375. else:
  376. await event_emitter(
  377. {
  378. "type": "status",
  379. "data": {
  380. "action": "web_search",
  381. "description": "No search results found",
  382. "done": True,
  383. "error": True,
  384. },
  385. }
  386. )
  387. return form_data
  388. async def chat_image_generation_handler(
  389. request: Request, form_data: dict, extra_params: dict, user
  390. ):
  391. __event_emitter__ = extra_params["__event_emitter__"]
  392. await __event_emitter__(
  393. {
  394. "type": "status",
  395. "data": {"description": "Generating an image", "done": False},
  396. }
  397. )
  398. messages = form_data["messages"]
  399. user_message = get_last_user_message(messages)
  400. prompt = user_message
  401. negative_prompt = ""
  402. if request.app.state.config.ENABLE_IMAGE_PROMPT_GENERATION:
  403. try:
  404. res = await generate_image_prompt(
  405. request,
  406. {
  407. "model": form_data["model"],
  408. "messages": messages,
  409. },
  410. user,
  411. )
  412. response = res["choices"][0]["message"]["content"]
  413. try:
  414. bracket_start = response.find("{")
  415. bracket_end = response.rfind("}") + 1
  416. if bracket_start == -1 or bracket_end == -1:
  417. raise Exception("No JSON object found in the response")
  418. response = response[bracket_start:bracket_end]
  419. response = json.loads(response)
  420. prompt = response.get("prompt", [])
  421. except Exception as e:
  422. prompt = user_message
  423. except Exception as e:
  424. log.exception(e)
  425. prompt = user_message
  426. system_message_content = ""
  427. try:
  428. images = await image_generations(
  429. request=request,
  430. form_data=GenerateImageForm(**{"prompt": prompt}),
  431. user=user,
  432. )
  433. await __event_emitter__(
  434. {
  435. "type": "status",
  436. "data": {"description": "Generated an image", "done": True},
  437. }
  438. )
  439. for image in images:
  440. await __event_emitter__(
  441. {
  442. "type": "message",
  443. "data": {"content": f"![Generated Image]({image['url']})\n"},
  444. }
  445. )
  446. system_message_content = "<context>User is shown the generated image, tell the user that the image has been generated</context>"
  447. except Exception as e:
  448. log.exception(e)
  449. await __event_emitter__(
  450. {
  451. "type": "status",
  452. "data": {
  453. "description": f"An error occurred while generating an image",
  454. "done": True,
  455. },
  456. }
  457. )
  458. system_message_content = "<context>Unable to generate an image, tell the user that an error occurred</context>"
  459. if system_message_content:
  460. form_data["messages"] = add_or_update_system_message(
  461. system_message_content, form_data["messages"]
  462. )
  463. return form_data
  464. async def chat_completion_files_handler(
  465. request: Request, body: dict, user: UserModel
  466. ) -> tuple[dict, dict[str, list]]:
  467. sources = []
  468. if files := body.get("metadata", {}).get("files", None):
  469. queries = []
  470. try:
  471. queries_response = await generate_queries(
  472. request,
  473. {
  474. "model": body["model"],
  475. "messages": body["messages"],
  476. "type": "retrieval",
  477. },
  478. user,
  479. )
  480. queries_response = queries_response["choices"][0]["message"]["content"]
  481. try:
  482. bracket_start = queries_response.find("{")
  483. bracket_end = queries_response.rfind("}") + 1
  484. if bracket_start == -1 or bracket_end == -1:
  485. raise Exception("No JSON object found in the response")
  486. queries_response = queries_response[bracket_start:bracket_end]
  487. queries_response = json.loads(queries_response)
  488. except Exception as e:
  489. queries_response = {"queries": [queries_response]}
  490. queries = queries_response.get("queries", [])
  491. except:
  492. pass
  493. if len(queries) == 0:
  494. queries = [get_last_user_message(body["messages"])]
  495. try:
  496. # Offload get_sources_from_files to a separate thread
  497. loop = asyncio.get_running_loop()
  498. with ThreadPoolExecutor() as executor:
  499. sources = await loop.run_in_executor(
  500. executor,
  501. lambda: get_sources_from_files(
  502. request=request,
  503. files=files,
  504. queries=queries,
  505. embedding_function=lambda query: request.app.state.EMBEDDING_FUNCTION(
  506. query, user=user
  507. ),
  508. k=request.app.state.config.TOP_K,
  509. reranking_function=request.app.state.rf,
  510. k_reranker=request.app.state.config.TOP_K_RERANKER,
  511. r=request.app.state.config.RELEVANCE_THRESHOLD,
  512. hybrid_search=request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  513. full_context=request.app.state.config.RAG_FULL_CONTEXT,
  514. ),
  515. )
  516. except Exception as e:
  517. log.exception(e)
  518. log.debug(f"rag_contexts:sources: {sources}")
  519. return body, {"sources": sources}
  520. def apply_params_to_form_data(form_data, model):
  521. params = form_data.pop("params", {})
  522. if model.get("ollama"):
  523. form_data["options"] = params
  524. if "format" in params:
  525. form_data["format"] = params["format"]
  526. if "keep_alive" in params:
  527. form_data["keep_alive"] = params["keep_alive"]
  528. else:
  529. if "seed" in params:
  530. form_data["seed"] = params["seed"]
  531. if "stop" in params:
  532. form_data["stop"] = params["stop"]
  533. if "temperature" in params:
  534. form_data["temperature"] = params["temperature"]
  535. if "max_tokens" in params:
  536. form_data["max_tokens"] = params["max_tokens"]
  537. if "top_p" in params:
  538. form_data["top_p"] = params["top_p"]
  539. if "frequency_penalty" in params:
  540. form_data["frequency_penalty"] = params["frequency_penalty"]
  541. if "reasoning_effort" in params:
  542. form_data["reasoning_effort"] = params["reasoning_effort"]
  543. if "logit_bias" in params:
  544. try:
  545. form_data["logit_bias"] = json.loads(
  546. convert_logit_bias_input_to_json(params["logit_bias"])
  547. )
  548. except Exception as e:
  549. print(f"Error parsing logit_bias: {e}")
  550. return form_data
  551. async def process_chat_payload(request, form_data, user, metadata, model):
  552. form_data = apply_params_to_form_data(form_data, model)
  553. log.debug(f"form_data: {form_data}")
  554. event_emitter = get_event_emitter(metadata)
  555. event_call = get_event_call(metadata)
  556. extra_params = {
  557. "__event_emitter__": event_emitter,
  558. "__event_call__": event_call,
  559. "__user__": {
  560. "id": user.id,
  561. "email": user.email,
  562. "name": user.name,
  563. "role": user.role,
  564. },
  565. "__metadata__": metadata,
  566. "__request__": request,
  567. "__model__": model,
  568. }
  569. # Initialize events to store additional event to be sent to the client
  570. # Initialize contexts and citation
  571. if getattr(request.state, "direct", False) and hasattr(request.state, "model"):
  572. models = {
  573. request.state.model["id"]: request.state.model,
  574. }
  575. else:
  576. models = request.app.state.MODELS
  577. task_model_id = get_task_model_id(
  578. form_data["model"],
  579. request.app.state.config.TASK_MODEL,
  580. request.app.state.config.TASK_MODEL_EXTERNAL,
  581. models,
  582. )
  583. events = []
  584. sources = []
  585. user_message = get_last_user_message(form_data["messages"])
  586. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  587. if model_knowledge:
  588. await event_emitter(
  589. {
  590. "type": "status",
  591. "data": {
  592. "action": "knowledge_search",
  593. "query": user_message,
  594. "done": False,
  595. },
  596. }
  597. )
  598. knowledge_files = []
  599. for item in model_knowledge:
  600. if item.get("collection_name"):
  601. knowledge_files.append(
  602. {
  603. "id": item.get("collection_name"),
  604. "name": item.get("name"),
  605. "legacy": True,
  606. }
  607. )
  608. elif item.get("collection_names"):
  609. knowledge_files.append(
  610. {
  611. "name": item.get("name"),
  612. "type": "collection",
  613. "collection_names": item.get("collection_names"),
  614. "legacy": True,
  615. }
  616. )
  617. else:
  618. knowledge_files.append(item)
  619. files = form_data.get("files", [])
  620. files.extend(knowledge_files)
  621. form_data["files"] = files
  622. variables = form_data.pop("variables", None)
  623. # Process the form_data through the pipeline
  624. try:
  625. form_data = await process_pipeline_inlet_filter(
  626. request, form_data, user, models
  627. )
  628. except Exception as e:
  629. raise e
  630. try:
  631. filter_functions = [
  632. Functions.get_function_by_id(filter_id)
  633. for filter_id in get_sorted_filter_ids(model)
  634. ]
  635. form_data, flags = await process_filter_functions(
  636. request=request,
  637. filter_functions=filter_functions,
  638. filter_type="inlet",
  639. form_data=form_data,
  640. extra_params=extra_params,
  641. )
  642. except Exception as e:
  643. raise Exception(f"Error: {e}")
  644. features = form_data.pop("features", None)
  645. if features:
  646. if "web_search" in features and features["web_search"]:
  647. form_data = await chat_web_search_handler(
  648. request, form_data, extra_params, user
  649. )
  650. if "image_generation" in features and features["image_generation"]:
  651. form_data = await chat_image_generation_handler(
  652. request, form_data, extra_params, user
  653. )
  654. if "code_interpreter" in features and features["code_interpreter"]:
  655. form_data["messages"] = add_or_update_user_message(
  656. (
  657. request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE
  658. if request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE != ""
  659. else DEFAULT_CODE_INTERPRETER_PROMPT
  660. ),
  661. form_data["messages"],
  662. )
  663. tool_ids = form_data.pop("tool_ids", None)
  664. files = form_data.pop("files", None)
  665. # Remove files duplicates
  666. if files:
  667. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  668. metadata = {
  669. **metadata,
  670. "tool_ids": tool_ids,
  671. "files": files,
  672. }
  673. form_data["metadata"] = metadata
  674. # Server side tools
  675. tool_ids = metadata.get("tool_ids", None)
  676. # Client side tools
  677. tool_servers = metadata.get("tool_servers", None)
  678. log.debug(f"{tool_ids=}")
  679. log.debug(f"{tool_servers=}")
  680. tools_dict = {}
  681. if tool_ids:
  682. tools_dict = get_tools(
  683. request,
  684. tool_ids,
  685. user,
  686. {
  687. **extra_params,
  688. "__model__": models[task_model_id],
  689. "__messages__": form_data["messages"],
  690. "__files__": metadata.get("files", []),
  691. },
  692. )
  693. log.info(f"{tools_dict=}")
  694. if tool_servers:
  695. for tool_server in tool_servers:
  696. tool_specs = tool_server.pop("specs", [])
  697. for tool in tool_specs:
  698. tools_dict[tool["name"]] = {
  699. "spec": tool,
  700. "direct": True,
  701. "server": tool_server,
  702. }
  703. if tools_dict:
  704. if metadata.get("function_calling") == "native":
  705. # If the function calling is native, then call the tools function calling handler
  706. metadata["tools"] = tools_dict
  707. form_data["tools"] = [
  708. {"type": "function", "function": tool.get("spec", {})}
  709. for tool in tools_dict.values()
  710. ]
  711. else:
  712. # If the function calling is not native, then call the tools function calling handler
  713. try:
  714. form_data, flags = await chat_completion_tools_handler(
  715. request, form_data, extra_params, user, models, tools_dict
  716. )
  717. sources.extend(flags.get("sources", []))
  718. except Exception as e:
  719. log.exception(e)
  720. try:
  721. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  722. sources.extend(flags.get("sources", []))
  723. except Exception as e:
  724. log.exception(e)
  725. # If context is not empty, insert it into the messages
  726. if len(sources) > 0:
  727. context_string = ""
  728. for source_idx, source in enumerate(sources):
  729. if "document" in source:
  730. for doc_idx, doc_context in enumerate(source["document"]):
  731. context_string += f"<source><source_id>{source_idx + 1}</source_id><source_context>{doc_context}</source_context></source>\n"
  732. context_string = context_string.strip()
  733. prompt = get_last_user_message(form_data["messages"])
  734. if prompt is None:
  735. raise Exception("No user message found")
  736. if (
  737. request.app.state.config.RELEVANCE_THRESHOLD == 0
  738. and context_string.strip() == ""
  739. ):
  740. log.debug(
  741. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  742. )
  743. # Workaround for Ollama 2.0+ system prompt issue
  744. # TODO: replace with add_or_update_system_message
  745. if model.get("owned_by") == "ollama":
  746. form_data["messages"] = prepend_to_first_user_message_content(
  747. rag_template(
  748. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  749. ),
  750. form_data["messages"],
  751. )
  752. else:
  753. form_data["messages"] = add_or_update_system_message(
  754. rag_template(
  755. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  756. ),
  757. form_data["messages"],
  758. )
  759. # If there are citations, add them to the data_items
  760. sources = [source for source in sources if source.get("source", {}).get("name", "")]
  761. if len(sources) > 0:
  762. events.append({"sources": sources})
  763. if model_knowledge:
  764. await event_emitter(
  765. {
  766. "type": "status",
  767. "data": {
  768. "action": "knowledge_search",
  769. "query": user_message,
  770. "done": True,
  771. "hidden": True,
  772. },
  773. }
  774. )
  775. return form_data, metadata, events
  776. async def process_chat_response(
  777. request, response, form_data, user, metadata, model, events, tasks
  778. ):
  779. async def background_tasks_handler():
  780. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  781. message = message_map.get(metadata["message_id"]) if message_map else None
  782. if message:
  783. messages = get_message_list(message_map, message.get("id"))
  784. if tasks and messages:
  785. if TASKS.TITLE_GENERATION in tasks:
  786. if tasks[TASKS.TITLE_GENERATION]:
  787. res = await generate_title(
  788. request,
  789. {
  790. "model": message["model"],
  791. "messages": messages,
  792. "chat_id": metadata["chat_id"],
  793. },
  794. user,
  795. )
  796. if res and isinstance(res, dict):
  797. if len(res.get("choices", [])) == 1:
  798. title_string = (
  799. res.get("choices", [])[0]
  800. .get("message", {})
  801. .get("content", message.get("content", "New Chat"))
  802. )
  803. else:
  804. title_string = ""
  805. title_string = title_string[
  806. title_string.find("{") : title_string.rfind("}") + 1
  807. ]
  808. try:
  809. title = json.loads(title_string).get(
  810. "title", "New Chat"
  811. )
  812. except Exception as e:
  813. title = ""
  814. if not title:
  815. title = messages[0].get("content", "New Chat")
  816. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  817. await event_emitter(
  818. {
  819. "type": "chat:title",
  820. "data": title,
  821. }
  822. )
  823. elif len(messages) == 2:
  824. title = messages[0].get("content", "New Chat")
  825. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  826. await event_emitter(
  827. {
  828. "type": "chat:title",
  829. "data": message.get("content", "New Chat"),
  830. }
  831. )
  832. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  833. res = await generate_chat_tags(
  834. request,
  835. {
  836. "model": message["model"],
  837. "messages": messages,
  838. "chat_id": metadata["chat_id"],
  839. },
  840. user,
  841. )
  842. if res and isinstance(res, dict):
  843. if len(res.get("choices", [])) == 1:
  844. tags_string = (
  845. res.get("choices", [])[0]
  846. .get("message", {})
  847. .get("content", "")
  848. )
  849. else:
  850. tags_string = ""
  851. tags_string = tags_string[
  852. tags_string.find("{") : tags_string.rfind("}") + 1
  853. ]
  854. try:
  855. tags = json.loads(tags_string).get("tags", [])
  856. Chats.update_chat_tags_by_id(
  857. metadata["chat_id"], tags, user
  858. )
  859. await event_emitter(
  860. {
  861. "type": "chat:tags",
  862. "data": tags,
  863. }
  864. )
  865. except Exception as e:
  866. pass
  867. event_emitter = None
  868. event_caller = None
  869. if (
  870. "session_id" in metadata
  871. and metadata["session_id"]
  872. and "chat_id" in metadata
  873. and metadata["chat_id"]
  874. and "message_id" in metadata
  875. and metadata["message_id"]
  876. ):
  877. event_emitter = get_event_emitter(metadata)
  878. event_caller = get_event_call(metadata)
  879. # Non-streaming response
  880. if not isinstance(response, StreamingResponse):
  881. if event_emitter:
  882. if "selected_model_id" in response:
  883. Chats.upsert_message_to_chat_by_id_and_message_id(
  884. metadata["chat_id"],
  885. metadata["message_id"],
  886. {
  887. "selectedModelId": response["selected_model_id"],
  888. },
  889. )
  890. if response.get("choices", [])[0].get("message", {}).get("content"):
  891. content = response["choices"][0]["message"]["content"]
  892. if content:
  893. await event_emitter(
  894. {
  895. "type": "chat:completion",
  896. "data": response,
  897. }
  898. )
  899. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  900. await event_emitter(
  901. {
  902. "type": "chat:completion",
  903. "data": {
  904. "done": True,
  905. "content": content,
  906. "title": title,
  907. },
  908. }
  909. )
  910. # Save message in the database
  911. Chats.upsert_message_to_chat_by_id_and_message_id(
  912. metadata["chat_id"],
  913. metadata["message_id"],
  914. {
  915. "content": content,
  916. },
  917. )
  918. # Send a webhook notification if the user is not active
  919. if get_active_status_by_user_id(user.id) is None:
  920. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  921. if webhook_url:
  922. post_webhook(
  923. request.app.state.WEBUI_NAME,
  924. webhook_url,
  925. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  926. {
  927. "action": "chat",
  928. "message": content,
  929. "title": title,
  930. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  931. },
  932. )
  933. await background_tasks_handler()
  934. return response
  935. else:
  936. return response
  937. # Non standard response
  938. if not any(
  939. content_type in response.headers["Content-Type"]
  940. for content_type in ["text/event-stream", "application/x-ndjson"]
  941. ):
  942. return response
  943. extra_params = {
  944. "__event_emitter__": event_emitter,
  945. "__event_call__": event_caller,
  946. "__user__": {
  947. "id": user.id,
  948. "email": user.email,
  949. "name": user.name,
  950. "role": user.role,
  951. },
  952. "__metadata__": metadata,
  953. "__request__": request,
  954. "__model__": model,
  955. }
  956. filter_functions = [
  957. Functions.get_function_by_id(filter_id)
  958. for filter_id in get_sorted_filter_ids(model)
  959. ]
  960. # Streaming response
  961. if event_emitter and event_caller:
  962. task_id = str(uuid4()) # Create a unique task ID.
  963. model_id = form_data.get("model", "")
  964. Chats.upsert_message_to_chat_by_id_and_message_id(
  965. metadata["chat_id"],
  966. metadata["message_id"],
  967. {
  968. "model": model_id,
  969. },
  970. )
  971. def split_content_and_whitespace(content):
  972. content_stripped = content.rstrip()
  973. original_whitespace = (
  974. content[len(content_stripped) :]
  975. if len(content) > len(content_stripped)
  976. else ""
  977. )
  978. return content_stripped, original_whitespace
  979. def is_opening_code_block(content):
  980. backtick_segments = content.split("```")
  981. # Even number of segments means the last backticks are opening a new block
  982. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  983. # Handle as a background task
  984. async def post_response_handler(response, events):
  985. def serialize_content_blocks(content_blocks, raw=False):
  986. content = ""
  987. for block in content_blocks:
  988. if block["type"] == "text":
  989. content = f"{content}{block['content'].strip()}\n"
  990. elif block["type"] == "tool_calls":
  991. attributes = block.get("attributes", {})
  992. block_content = block.get("content", [])
  993. results = block.get("results", [])
  994. if results:
  995. result_display_content = ""
  996. for result in results:
  997. tool_call_id = result.get("tool_call_id", "")
  998. tool_name = ""
  999. for tool_call in block_content:
  1000. if tool_call.get("id", "") == tool_call_id:
  1001. tool_name = tool_call.get("function", {}).get(
  1002. "name", ""
  1003. )
  1004. break
  1005. result_display_content = f"{result_display_content}\n> {tool_name}: {result.get('content', '')}"
  1006. if not raw:
  1007. content = f'{content}\n<details type="tool_calls" done="true" content="{html.escape(json.dumps(block_content))}" results="{html.escape(json.dumps(results))}">\n<summary>Tool Executed</summary>\n{result_display_content}\n</details>\n'
  1008. else:
  1009. tool_calls_display_content = ""
  1010. for tool_call in block_content:
  1011. tool_calls_display_content = f"{tool_calls_display_content}\n> Executing {tool_call.get('function', {}).get('name', '')}"
  1012. if not raw:
  1013. content = f'{content}\n<details type="tool_calls" done="false" content="{html.escape(json.dumps(block_content))}">\n<summary>Tool Executing...</summary>\n{tool_calls_display_content}\n</details>\n'
  1014. elif block["type"] == "reasoning":
  1015. reasoning_display_content = "\n".join(
  1016. (f"> {line}" if not line.startswith(">") else line)
  1017. for line in block["content"].splitlines()
  1018. )
  1019. reasoning_duration = block.get("duration", None)
  1020. if reasoning_duration is not None:
  1021. if raw:
  1022. content = f'{content}\n<{block["start_tag"]}>{block["content"]}<{block["end_tag"]}>\n'
  1023. else:
  1024. content = f'{content}\n<details type="reasoning" done="true" duration="{reasoning_duration}">\n<summary>Thought for {reasoning_duration} seconds</summary>\n{reasoning_display_content}\n</details>\n'
  1025. else:
  1026. if raw:
  1027. content = f'{content}\n<{block["start_tag"]}>{block["content"]}<{block["end_tag"]}>\n'
  1028. else:
  1029. content = f'{content}\n<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1030. elif block["type"] == "code_interpreter":
  1031. attributes = block.get("attributes", {})
  1032. output = block.get("output", None)
  1033. lang = attributes.get("lang", "")
  1034. content_stripped, original_whitespace = (
  1035. split_content_and_whitespace(content)
  1036. )
  1037. if is_opening_code_block(content_stripped):
  1038. # Remove trailing backticks that would open a new block
  1039. content = (
  1040. content_stripped.rstrip("`").rstrip()
  1041. + original_whitespace
  1042. )
  1043. else:
  1044. # Keep content as is - either closing backticks or no backticks
  1045. content = content_stripped + original_whitespace
  1046. if output:
  1047. output = html.escape(json.dumps(output))
  1048. if raw:
  1049. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1050. else:
  1051. content = f'{content}\n<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1052. else:
  1053. if raw:
  1054. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1055. else:
  1056. content = f'{content}\n<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1057. else:
  1058. block_content = str(block["content"]).strip()
  1059. content = f"{content}{block['type']}: {block_content}\n"
  1060. return content.strip()
  1061. def convert_content_blocks_to_messages(content_blocks):
  1062. messages = []
  1063. temp_blocks = []
  1064. for idx, block in enumerate(content_blocks):
  1065. if block["type"] == "tool_calls":
  1066. messages.append(
  1067. {
  1068. "role": "assistant",
  1069. "content": serialize_content_blocks(temp_blocks),
  1070. "tool_calls": block.get("content"),
  1071. }
  1072. )
  1073. results = block.get("results", [])
  1074. for result in results:
  1075. messages.append(
  1076. {
  1077. "role": "tool",
  1078. "tool_call_id": result["tool_call_id"],
  1079. "content": result["content"],
  1080. }
  1081. )
  1082. temp_blocks = []
  1083. else:
  1084. temp_blocks.append(block)
  1085. if temp_blocks:
  1086. content = serialize_content_blocks(temp_blocks)
  1087. if content:
  1088. messages.append(
  1089. {
  1090. "role": "assistant",
  1091. "content": content,
  1092. }
  1093. )
  1094. return messages
  1095. def tag_content_handler(content_type, tags, content, content_blocks):
  1096. end_flag = False
  1097. def extract_attributes(tag_content):
  1098. """Extract attributes from a tag if they exist."""
  1099. attributes = {}
  1100. if not tag_content: # Ensure tag_content is not None
  1101. return attributes
  1102. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1103. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1104. for key, value in matches:
  1105. attributes[key] = value
  1106. return attributes
  1107. if content_blocks[-1]["type"] == "text":
  1108. for start_tag, end_tag in tags:
  1109. # Match start tag e.g., <tag> or <tag attr="value">
  1110. start_tag_pattern = rf"<{re.escape(start_tag)}(\s.*?)?>"
  1111. match = re.search(start_tag_pattern, content)
  1112. if match:
  1113. attr_content = (
  1114. match.group(1) if match.group(1) else ""
  1115. ) # Ensure it's not None
  1116. attributes = extract_attributes(
  1117. attr_content
  1118. ) # Extract attributes safely
  1119. # Capture everything before and after the matched tag
  1120. before_tag = content[
  1121. : match.start()
  1122. ] # Content before opening tag
  1123. after_tag = content[
  1124. match.end() :
  1125. ] # Content after opening tag
  1126. # Remove the start tag and after from the currently handling text block
  1127. content_blocks[-1]["content"] = content_blocks[-1][
  1128. "content"
  1129. ].replace(match.group(0) + after_tag, "")
  1130. if before_tag:
  1131. content_blocks[-1]["content"] = before_tag
  1132. if not content_blocks[-1]["content"]:
  1133. content_blocks.pop()
  1134. # Append the new block
  1135. content_blocks.append(
  1136. {
  1137. "type": content_type,
  1138. "start_tag": start_tag,
  1139. "end_tag": end_tag,
  1140. "attributes": attributes,
  1141. "content": "",
  1142. "started_at": time.time(),
  1143. }
  1144. )
  1145. if after_tag:
  1146. content_blocks[-1]["content"] = after_tag
  1147. break
  1148. elif content_blocks[-1]["type"] == content_type:
  1149. start_tag = content_blocks[-1]["start_tag"]
  1150. end_tag = content_blocks[-1]["end_tag"]
  1151. # Match end tag e.g., </tag>
  1152. end_tag_pattern = rf"<{re.escape(end_tag)}>"
  1153. # Check if the content has the end tag
  1154. if re.search(end_tag_pattern, content):
  1155. end_flag = True
  1156. block_content = content_blocks[-1]["content"]
  1157. # Strip start and end tags from the content
  1158. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1159. block_content = re.sub(
  1160. start_tag_pattern, "", block_content
  1161. ).strip()
  1162. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1163. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1164. # Content inside the tag
  1165. block_content = (
  1166. split_content[0].strip() if split_content else ""
  1167. )
  1168. # Leftover content (everything after `</tag>`)
  1169. leftover_content = (
  1170. split_content[1].strip() if len(split_content) > 1 else ""
  1171. )
  1172. if block_content:
  1173. content_blocks[-1]["content"] = block_content
  1174. content_blocks[-1]["ended_at"] = time.time()
  1175. content_blocks[-1]["duration"] = int(
  1176. content_blocks[-1]["ended_at"]
  1177. - content_blocks[-1]["started_at"]
  1178. )
  1179. # Reset the content_blocks by appending a new text block
  1180. if content_type != "code_interpreter":
  1181. if leftover_content:
  1182. content_blocks.append(
  1183. {
  1184. "type": "text",
  1185. "content": leftover_content,
  1186. }
  1187. )
  1188. else:
  1189. content_blocks.append(
  1190. {
  1191. "type": "text",
  1192. "content": "",
  1193. }
  1194. )
  1195. else:
  1196. # Remove the block if content is empty
  1197. content_blocks.pop()
  1198. if leftover_content:
  1199. content_blocks.append(
  1200. {
  1201. "type": "text",
  1202. "content": leftover_content,
  1203. }
  1204. )
  1205. else:
  1206. content_blocks.append(
  1207. {
  1208. "type": "text",
  1209. "content": "",
  1210. }
  1211. )
  1212. # Clean processed content
  1213. content = re.sub(
  1214. rf"<{re.escape(start_tag)}(.*?)>(.|\n)*?<{re.escape(end_tag)}>",
  1215. "",
  1216. content,
  1217. flags=re.DOTALL,
  1218. )
  1219. return content, content_blocks, end_flag
  1220. message = Chats.get_message_by_id_and_message_id(
  1221. metadata["chat_id"], metadata["message_id"]
  1222. )
  1223. tool_calls = []
  1224. last_assistant_message = None
  1225. try:
  1226. if form_data["messages"][-1]["role"] == "assistant":
  1227. last_assistant_message = get_last_assistant_message(
  1228. form_data["messages"]
  1229. )
  1230. except Exception as e:
  1231. pass
  1232. content = (
  1233. message.get("content", "")
  1234. if message
  1235. else last_assistant_message if last_assistant_message else ""
  1236. )
  1237. content_blocks = [
  1238. {
  1239. "type": "text",
  1240. "content": content,
  1241. }
  1242. ]
  1243. # We might want to disable this by default
  1244. DETECT_REASONING = True
  1245. DETECT_SOLUTION = True
  1246. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1247. "code_interpreter", False
  1248. )
  1249. reasoning_tags = [
  1250. ("think", "/think"),
  1251. ("thinking", "/thinking"),
  1252. ("reason", "/reason"),
  1253. ("reasoning", "/reasoning"),
  1254. ("thought", "/thought"),
  1255. ("Thought", "/Thought"),
  1256. ("|begin_of_thought|", "|end_of_thought|"),
  1257. ]
  1258. code_interpreter_tags = [("code_interpreter", "/code_interpreter")]
  1259. solution_tags = [("|begin_of_solution|", "|end_of_solution|")]
  1260. try:
  1261. for event in events:
  1262. await event_emitter(
  1263. {
  1264. "type": "chat:completion",
  1265. "data": event,
  1266. }
  1267. )
  1268. # Save message in the database
  1269. Chats.upsert_message_to_chat_by_id_and_message_id(
  1270. metadata["chat_id"],
  1271. metadata["message_id"],
  1272. {
  1273. **event,
  1274. },
  1275. )
  1276. async def stream_body_handler(response):
  1277. nonlocal content
  1278. nonlocal content_blocks
  1279. response_tool_calls = []
  1280. async for line in response.body_iterator:
  1281. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1282. data = line
  1283. # Skip empty lines
  1284. if not data.strip():
  1285. continue
  1286. # "data:" is the prefix for each event
  1287. if not data.startswith("data:"):
  1288. continue
  1289. # Remove the prefix
  1290. data = data[len("data:") :].strip()
  1291. try:
  1292. data = json.loads(data)
  1293. data, _ = await process_filter_functions(
  1294. request=request,
  1295. filter_functions=filter_functions,
  1296. filter_type="stream",
  1297. form_data=data,
  1298. extra_params=extra_params,
  1299. )
  1300. if data:
  1301. if "selected_model_id" in data:
  1302. model_id = data["selected_model_id"]
  1303. Chats.upsert_message_to_chat_by_id_and_message_id(
  1304. metadata["chat_id"],
  1305. metadata["message_id"],
  1306. {
  1307. "selectedModelId": model_id,
  1308. },
  1309. )
  1310. else:
  1311. choices = data.get("choices", [])
  1312. if not choices:
  1313. usage = data.get("usage", {})
  1314. if usage:
  1315. await event_emitter(
  1316. {
  1317. "type": "chat:completion",
  1318. "data": {
  1319. "usage": usage,
  1320. },
  1321. }
  1322. )
  1323. continue
  1324. delta = choices[0].get("delta", {})
  1325. delta_tool_calls = delta.get("tool_calls", None)
  1326. if delta_tool_calls:
  1327. for delta_tool_call in delta_tool_calls:
  1328. tool_call_index = delta_tool_call.get(
  1329. "index"
  1330. )
  1331. if tool_call_index is not None:
  1332. if (
  1333. len(response_tool_calls)
  1334. <= tool_call_index
  1335. ):
  1336. response_tool_calls.append(
  1337. delta_tool_call
  1338. )
  1339. else:
  1340. delta_name = delta_tool_call.get(
  1341. "function", {}
  1342. ).get("name")
  1343. delta_arguments = (
  1344. delta_tool_call.get(
  1345. "function", {}
  1346. ).get("arguments")
  1347. )
  1348. if delta_name:
  1349. response_tool_calls[
  1350. tool_call_index
  1351. ]["function"][
  1352. "name"
  1353. ] += delta_name
  1354. if delta_arguments:
  1355. response_tool_calls[
  1356. tool_call_index
  1357. ]["function"][
  1358. "arguments"
  1359. ] += delta_arguments
  1360. value = delta.get("content")
  1361. reasoning_content = delta.get(
  1362. "reasoning_content"
  1363. ) or delta.get("reasoning")
  1364. if reasoning_content:
  1365. if (
  1366. not content_blocks
  1367. or content_blocks[-1]["type"] != "reasoning"
  1368. ):
  1369. reasoning_block = {
  1370. "type": "reasoning",
  1371. "start_tag": "think",
  1372. "end_tag": "/think",
  1373. "attributes": {
  1374. "type": "reasoning_content"
  1375. },
  1376. "content": "",
  1377. "started_at": time.time(),
  1378. }
  1379. content_blocks.append(reasoning_block)
  1380. else:
  1381. reasoning_block = content_blocks[-1]
  1382. reasoning_block["content"] += reasoning_content
  1383. data = {
  1384. "content": serialize_content_blocks(
  1385. content_blocks
  1386. )
  1387. }
  1388. if value:
  1389. if (
  1390. content_blocks
  1391. and content_blocks[-1]["type"]
  1392. == "reasoning"
  1393. and content_blocks[-1]
  1394. .get("attributes", {})
  1395. .get("type")
  1396. == "reasoning_content"
  1397. ):
  1398. reasoning_block = content_blocks[-1]
  1399. reasoning_block["ended_at"] = time.time()
  1400. reasoning_block["duration"] = int(
  1401. reasoning_block["ended_at"]
  1402. - reasoning_block["started_at"]
  1403. )
  1404. content_blocks.append(
  1405. {
  1406. "type": "text",
  1407. "content": "",
  1408. }
  1409. )
  1410. content = f"{content}{value}"
  1411. if not content_blocks:
  1412. content_blocks.append(
  1413. {
  1414. "type": "text",
  1415. "content": "",
  1416. }
  1417. )
  1418. content_blocks[-1]["content"] = (
  1419. content_blocks[-1]["content"] + value
  1420. )
  1421. if DETECT_REASONING:
  1422. content, content_blocks, _ = (
  1423. tag_content_handler(
  1424. "reasoning",
  1425. reasoning_tags,
  1426. content,
  1427. content_blocks,
  1428. )
  1429. )
  1430. if DETECT_CODE_INTERPRETER:
  1431. content, content_blocks, end = (
  1432. tag_content_handler(
  1433. "code_interpreter",
  1434. code_interpreter_tags,
  1435. content,
  1436. content_blocks,
  1437. )
  1438. )
  1439. if end:
  1440. break
  1441. if DETECT_SOLUTION:
  1442. content, content_blocks, _ = (
  1443. tag_content_handler(
  1444. "solution",
  1445. solution_tags,
  1446. content,
  1447. content_blocks,
  1448. )
  1449. )
  1450. if ENABLE_REALTIME_CHAT_SAVE:
  1451. # Save message in the database
  1452. Chats.upsert_message_to_chat_by_id_and_message_id(
  1453. metadata["chat_id"],
  1454. metadata["message_id"],
  1455. {
  1456. "content": serialize_content_blocks(
  1457. content_blocks
  1458. ),
  1459. },
  1460. )
  1461. else:
  1462. data = {
  1463. "content": serialize_content_blocks(
  1464. content_blocks
  1465. ),
  1466. }
  1467. await event_emitter(
  1468. {
  1469. "type": "chat:completion",
  1470. "data": data,
  1471. }
  1472. )
  1473. except Exception as e:
  1474. done = "data: [DONE]" in line
  1475. if done:
  1476. pass
  1477. else:
  1478. log.debug("Error: ", e)
  1479. continue
  1480. if content_blocks:
  1481. # Clean up the last text block
  1482. if content_blocks[-1]["type"] == "text":
  1483. content_blocks[-1]["content"] = content_blocks[-1][
  1484. "content"
  1485. ].strip()
  1486. if not content_blocks[-1]["content"]:
  1487. content_blocks.pop()
  1488. if not content_blocks:
  1489. content_blocks.append(
  1490. {
  1491. "type": "text",
  1492. "content": "",
  1493. }
  1494. )
  1495. if response_tool_calls:
  1496. tool_calls.append(response_tool_calls)
  1497. if response.background:
  1498. await response.background()
  1499. await stream_body_handler(response)
  1500. MAX_TOOL_CALL_RETRIES = 5
  1501. tool_call_retries = 0
  1502. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1503. tool_call_retries += 1
  1504. response_tool_calls = tool_calls.pop(0)
  1505. content_blocks.append(
  1506. {
  1507. "type": "tool_calls",
  1508. "content": response_tool_calls,
  1509. }
  1510. )
  1511. await event_emitter(
  1512. {
  1513. "type": "chat:completion",
  1514. "data": {
  1515. "content": serialize_content_blocks(content_blocks),
  1516. },
  1517. }
  1518. )
  1519. tools = metadata.get("tools", {})
  1520. results = []
  1521. for tool_call in response_tool_calls:
  1522. tool_call_id = tool_call.get("id", "")
  1523. tool_name = tool_call.get("function", {}).get("name", "")
  1524. tool_function_params = {}
  1525. try:
  1526. # json.loads cannot be used because some models do not produce valid JSON
  1527. tool_function_params = ast.literal_eval(
  1528. tool_call.get("function", {}).get("arguments", "{}")
  1529. )
  1530. except Exception as e:
  1531. log.debug(e)
  1532. tool_result = None
  1533. if tool_name in tools:
  1534. tool = tools[tool_name]
  1535. spec = tool.get("spec", {})
  1536. try:
  1537. allowed_params = (
  1538. spec.get("parameters", {})
  1539. .get("properties", {})
  1540. .keys()
  1541. )
  1542. tool_function = tool["callable"]
  1543. tool_function_params = {
  1544. k: v
  1545. for k, v in tool_function_params.items()
  1546. if k in allowed_params
  1547. }
  1548. if tool.get("direct", False):
  1549. tool_result = await tool_function(
  1550. **tool_function_params
  1551. )
  1552. else:
  1553. tool_result = await event_caller(
  1554. {
  1555. "type": "execute:tool",
  1556. "data": {
  1557. "id": str(uuid4()),
  1558. "name": tool_name,
  1559. "params": tool_function_params,
  1560. "tool": tool,
  1561. "server": tool.get("server", {}),
  1562. "session_id": metadata.get(
  1563. "session_id", None
  1564. ),
  1565. },
  1566. }
  1567. )
  1568. except Exception as e:
  1569. tool_result = str(e)
  1570. results.append(
  1571. {
  1572. "tool_call_id": tool_call_id,
  1573. "content": tool_result,
  1574. }
  1575. )
  1576. content_blocks[-1]["results"] = results
  1577. content_blocks.append(
  1578. {
  1579. "type": "text",
  1580. "content": "",
  1581. }
  1582. )
  1583. await event_emitter(
  1584. {
  1585. "type": "chat:completion",
  1586. "data": {
  1587. "content": serialize_content_blocks(content_blocks),
  1588. },
  1589. }
  1590. )
  1591. try:
  1592. res = await generate_chat_completion(
  1593. request,
  1594. {
  1595. "model": model_id,
  1596. "stream": True,
  1597. "tools": form_data["tools"],
  1598. "messages": [
  1599. *form_data["messages"],
  1600. *convert_content_blocks_to_messages(content_blocks),
  1601. ],
  1602. },
  1603. user,
  1604. )
  1605. if isinstance(res, StreamingResponse):
  1606. await stream_body_handler(res)
  1607. else:
  1608. break
  1609. except Exception as e:
  1610. log.debug(e)
  1611. break
  1612. if DETECT_CODE_INTERPRETER:
  1613. MAX_RETRIES = 5
  1614. retries = 0
  1615. while (
  1616. content_blocks[-1]["type"] == "code_interpreter"
  1617. and retries < MAX_RETRIES
  1618. ):
  1619. await event_emitter(
  1620. {
  1621. "type": "chat:completion",
  1622. "data": {
  1623. "content": serialize_content_blocks(content_blocks),
  1624. },
  1625. }
  1626. )
  1627. retries += 1
  1628. log.debug(f"Attempt count: {retries}")
  1629. output = ""
  1630. try:
  1631. if content_blocks[-1]["attributes"].get("type") == "code":
  1632. code = content_blocks[-1]["content"]
  1633. if (
  1634. request.app.state.config.CODE_INTERPRETER_ENGINE
  1635. == "pyodide"
  1636. ):
  1637. output = await event_caller(
  1638. {
  1639. "type": "execute:python",
  1640. "data": {
  1641. "id": str(uuid4()),
  1642. "code": code,
  1643. "session_id": metadata.get(
  1644. "session_id", None
  1645. ),
  1646. },
  1647. }
  1648. )
  1649. elif (
  1650. request.app.state.config.CODE_INTERPRETER_ENGINE
  1651. == "jupyter"
  1652. ):
  1653. output = await execute_code_jupyter(
  1654. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  1655. code,
  1656. (
  1657. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  1658. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1659. == "token"
  1660. else None
  1661. ),
  1662. (
  1663. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  1664. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1665. == "password"
  1666. else None
  1667. ),
  1668. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  1669. )
  1670. else:
  1671. output = {
  1672. "stdout": "Code interpreter engine not configured."
  1673. }
  1674. log.debug(f"Code interpreter output: {output}")
  1675. if isinstance(output, dict):
  1676. stdout = output.get("stdout", "")
  1677. if isinstance(stdout, str):
  1678. stdoutLines = stdout.split("\n")
  1679. for idx, line in enumerate(stdoutLines):
  1680. if "data:image/png;base64" in line:
  1681. id = str(uuid4())
  1682. # ensure the path exists
  1683. os.makedirs(
  1684. os.path.join(CACHE_DIR, "images"),
  1685. exist_ok=True,
  1686. )
  1687. image_path = os.path.join(
  1688. CACHE_DIR,
  1689. f"images/{id}.png",
  1690. )
  1691. with open(image_path, "wb") as f:
  1692. f.write(
  1693. base64.b64decode(
  1694. line.split(",")[1]
  1695. )
  1696. )
  1697. stdoutLines[idx] = (
  1698. f"![Output Image {idx}](/cache/images/{id}.png)"
  1699. )
  1700. output["stdout"] = "\n".join(stdoutLines)
  1701. result = output.get("result", "")
  1702. if isinstance(result, str):
  1703. resultLines = result.split("\n")
  1704. for idx, line in enumerate(resultLines):
  1705. if "data:image/png;base64" in line:
  1706. id = str(uuid4())
  1707. # ensure the path exists
  1708. os.makedirs(
  1709. os.path.join(CACHE_DIR, "images"),
  1710. exist_ok=True,
  1711. )
  1712. image_path = os.path.join(
  1713. CACHE_DIR,
  1714. f"images/{id}.png",
  1715. )
  1716. with open(image_path, "wb") as f:
  1717. f.write(
  1718. base64.b64decode(
  1719. line.split(",")[1]
  1720. )
  1721. )
  1722. resultLines[idx] = (
  1723. f"![Output Image {idx}](/cache/images/{id}.png)"
  1724. )
  1725. output["result"] = "\n".join(resultLines)
  1726. except Exception as e:
  1727. output = str(e)
  1728. content_blocks[-1]["output"] = output
  1729. content_blocks.append(
  1730. {
  1731. "type": "text",
  1732. "content": "",
  1733. }
  1734. )
  1735. await event_emitter(
  1736. {
  1737. "type": "chat:completion",
  1738. "data": {
  1739. "content": serialize_content_blocks(content_blocks),
  1740. },
  1741. }
  1742. )
  1743. log.info(f"content_blocks={content_blocks}")
  1744. log.info(
  1745. f"serialize_content_blocks={serialize_content_blocks(content_blocks)}"
  1746. )
  1747. try:
  1748. res = await generate_chat_completion(
  1749. request,
  1750. {
  1751. "model": model_id,
  1752. "stream": True,
  1753. "messages": [
  1754. *form_data["messages"],
  1755. {
  1756. "role": "assistant",
  1757. "content": serialize_content_blocks(
  1758. content_blocks, raw=True
  1759. ),
  1760. },
  1761. ],
  1762. },
  1763. user,
  1764. )
  1765. if isinstance(res, StreamingResponse):
  1766. await stream_body_handler(res)
  1767. else:
  1768. break
  1769. except Exception as e:
  1770. log.debug(e)
  1771. break
  1772. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1773. data = {
  1774. "done": True,
  1775. "content": serialize_content_blocks(content_blocks),
  1776. "title": title,
  1777. }
  1778. if not ENABLE_REALTIME_CHAT_SAVE:
  1779. # Save message in the database
  1780. Chats.upsert_message_to_chat_by_id_and_message_id(
  1781. metadata["chat_id"],
  1782. metadata["message_id"],
  1783. {
  1784. "content": serialize_content_blocks(content_blocks),
  1785. },
  1786. )
  1787. # Send a webhook notification if the user is not active
  1788. if get_active_status_by_user_id(user.id) is None:
  1789. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1790. if webhook_url:
  1791. post_webhook(
  1792. request.app.state.WEBUI_NAME,
  1793. webhook_url,
  1794. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1795. {
  1796. "action": "chat",
  1797. "message": content,
  1798. "title": title,
  1799. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1800. },
  1801. )
  1802. await event_emitter(
  1803. {
  1804. "type": "chat:completion",
  1805. "data": data,
  1806. }
  1807. )
  1808. await background_tasks_handler()
  1809. except asyncio.CancelledError:
  1810. log.warning("Task was cancelled!")
  1811. await event_emitter({"type": "task-cancelled"})
  1812. if not ENABLE_REALTIME_CHAT_SAVE:
  1813. # Save message in the database
  1814. Chats.upsert_message_to_chat_by_id_and_message_id(
  1815. metadata["chat_id"],
  1816. metadata["message_id"],
  1817. {
  1818. "content": serialize_content_blocks(content_blocks),
  1819. },
  1820. )
  1821. if response.background is not None:
  1822. await response.background()
  1823. # background_tasks.add_task(post_response_handler, response, events)
  1824. task_id, _ = create_task(post_response_handler(response, events))
  1825. return {"status": True, "task_id": task_id}
  1826. else:
  1827. # Fallback to the original response
  1828. async def stream_wrapper(original_generator, events):
  1829. def wrap_item(item):
  1830. return f"data: {item}\n\n"
  1831. for event in events:
  1832. event, _ = await process_filter_functions(
  1833. request=request,
  1834. filter_functions=filter_functions,
  1835. filter_type="stream",
  1836. form_data=event,
  1837. extra_params=extra_params,
  1838. )
  1839. if event:
  1840. yield wrap_item(json.dumps(event))
  1841. async for data in original_generator:
  1842. data, _ = await process_filter_functions(
  1843. request=request,
  1844. filter_functions=filter_functions,
  1845. filter_type="stream",
  1846. form_data=data,
  1847. extra_params=extra_params,
  1848. )
  1849. if data:
  1850. yield data
  1851. return StreamingResponse(
  1852. stream_wrapper(response.body_iterator, events),
  1853. headers=dict(response.headers),
  1854. background=response.background,
  1855. )