middleware.py 84 KB

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