middleware.py 71 KB

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