middleware.py 91 KB

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