middleware.py 66 KB

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