middleware.py 69 KB

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