middleware.py 68 KB

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