middleware.py 69 KB

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