middleware.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812
  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 occured 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 occured</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. handler_type="inlet",
  577. filter_ids=get_sorted_filter_ids(model),
  578. request=request,
  579. 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 = content[len(content_stripped):] if len(content) > len(content_stripped) else ''
  872. return content_stripped, original_whitespace
  873. def is_opening_code_block(content):
  874. backtick_segments = content.split('```')
  875. # Even number of segments means the last backticks are opening a new block
  876. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  877. # Handle as a background task
  878. async def post_response_handler(response, events):
  879. def serialize_content_blocks(content_blocks, raw=False):
  880. content = ""
  881. for block in content_blocks:
  882. if block["type"] == "text":
  883. content = f"{content}{block['content'].strip()}\n"
  884. elif block["type"] == "tool_calls":
  885. attributes = block.get("attributes", {})
  886. block_content = block.get("content", [])
  887. results = block.get("results", [])
  888. if results:
  889. result_display_content = ""
  890. for result in results:
  891. tool_call_id = result.get("tool_call_id", "")
  892. tool_name = ""
  893. for tool_call in block_content:
  894. if tool_call.get("id", "") == tool_call_id:
  895. tool_name = tool_call.get("function", {}).get(
  896. "name", ""
  897. )
  898. break
  899. result_display_content = f"{result_display_content}\n> {tool_name}: {result.get('content', '')}"
  900. if not raw:
  901. 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'
  902. else:
  903. tool_calls_display_content = ""
  904. for tool_call in block_content:
  905. tool_calls_display_content = f"{tool_calls_display_content}\n> Executing {tool_call.get('function', {}).get('name', '')}"
  906. if not raw:
  907. 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'
  908. elif block["type"] == "reasoning":
  909. reasoning_display_content = "\n".join(
  910. (f"> {line}" if not line.startswith(">") else line)
  911. for line in block["content"].splitlines()
  912. )
  913. reasoning_duration = block.get("duration", None)
  914. if reasoning_duration is not None:
  915. if raw:
  916. content = f'{content}\n<{block["tag"]}>{block["content"]}</{block["tag"]}>\n'
  917. else:
  918. 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'
  919. else:
  920. if raw:
  921. content = f'{content}\n<{block["tag"]}>{block["content"]}</{block["tag"]}>\n'
  922. else:
  923. content = f'{content}\n<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  924. elif block["type"] == "code_interpreter":
  925. attributes = block.get("attributes", {})
  926. output = block.get("output", None)
  927. lang = attributes.get("lang", "")
  928. content_stripped, original_whitespace = split_content_and_whitespace(content)
  929. if is_opening_code_block(content_stripped):
  930. # Remove trailing backticks that would open a new block
  931. content = content_stripped.rstrip('`').rstrip() + original_whitespace
  932. else:
  933. # Keep content as is - either closing backticks or no backticks
  934. content = content_stripped + original_whitespace
  935. if output:
  936. output = html.escape(json.dumps(output))
  937. if raw:
  938. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  939. else:
  940. 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'
  941. else:
  942. if raw:
  943. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  944. else:
  945. content = f'{content}\n<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  946. else:
  947. block_content = str(block["content"]).strip()
  948. content = f"{content}{block['type']}: {block_content}\n"
  949. return content.strip()
  950. def tag_content_handler(content_type, tags, content, content_blocks):
  951. end_flag = False
  952. def extract_attributes(tag_content):
  953. """Extract attributes from a tag if they exist."""
  954. attributes = {}
  955. if not tag_content: # Ensure tag_content is not None
  956. return attributes
  957. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  958. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  959. for key, value in matches:
  960. attributes[key] = value
  961. return attributes
  962. if content_blocks[-1]["type"] == "text":
  963. for tag in tags:
  964. # Match start tag e.g., <tag> or <tag attr="value">
  965. start_tag_pattern = rf"<{tag}(\s.*?)?>"
  966. match = re.search(start_tag_pattern, content)
  967. if match:
  968. attr_content = (
  969. match.group(1) if match.group(1) else ""
  970. ) # Ensure it's not None
  971. attributes = extract_attributes(
  972. attr_content
  973. ) # Extract attributes safely
  974. # Capture everything before and after the matched tag
  975. before_tag = content[
  976. : match.start()
  977. ] # Content before opening tag
  978. after_tag = content[
  979. match.end() :
  980. ] # Content after opening tag
  981. # Remove the start tag from the currently handling text block
  982. content_blocks[-1]["content"] = content_blocks[-1][
  983. "content"
  984. ].replace(match.group(0), "")
  985. if before_tag:
  986. content_blocks[-1]["content"] = before_tag
  987. if not content_blocks[-1]["content"]:
  988. content_blocks.pop()
  989. # Append the new block
  990. content_blocks.append(
  991. {
  992. "type": content_type,
  993. "tag": tag,
  994. "attributes": attributes,
  995. "content": "",
  996. "started_at": time.time(),
  997. }
  998. )
  999. if after_tag:
  1000. content_blocks[-1]["content"] = after_tag
  1001. break
  1002. elif content_blocks[-1]["type"] == content_type:
  1003. tag = content_blocks[-1]["tag"]
  1004. # Match end tag e.g., </tag>
  1005. end_tag_pattern = rf"</{tag}>"
  1006. # Check if the content has the end tag
  1007. if re.search(end_tag_pattern, content):
  1008. end_flag = True
  1009. block_content = content_blocks[-1]["content"]
  1010. # Strip start and end tags from the content
  1011. start_tag_pattern = rf"<{tag}(.*?)>"
  1012. block_content = re.sub(
  1013. start_tag_pattern, "", block_content
  1014. ).strip()
  1015. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1016. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1017. # Content inside the tag
  1018. block_content = (
  1019. split_content[0].strip() if split_content else ""
  1020. )
  1021. # Leftover content (everything after `</tag>`)
  1022. leftover_content = (
  1023. split_content[1].strip() if len(split_content) > 1 else ""
  1024. )
  1025. if block_content:
  1026. content_blocks[-1]["content"] = block_content
  1027. content_blocks[-1]["ended_at"] = time.time()
  1028. content_blocks[-1]["duration"] = int(
  1029. content_blocks[-1]["ended_at"]
  1030. - content_blocks[-1]["started_at"]
  1031. )
  1032. # Reset the content_blocks by appending a new text block
  1033. if content_type != "code_interpreter":
  1034. if leftover_content:
  1035. content_blocks.append(
  1036. {
  1037. "type": "text",
  1038. "content": leftover_content,
  1039. }
  1040. )
  1041. else:
  1042. content_blocks.append(
  1043. {
  1044. "type": "text",
  1045. "content": "",
  1046. }
  1047. )
  1048. else:
  1049. # Remove the block if content is empty
  1050. content_blocks.pop()
  1051. if leftover_content:
  1052. content_blocks.append(
  1053. {
  1054. "type": "text",
  1055. "content": leftover_content,
  1056. }
  1057. )
  1058. else:
  1059. content_blocks.append(
  1060. {
  1061. "type": "text",
  1062. "content": "",
  1063. }
  1064. )
  1065. # Clean processed content
  1066. content = re.sub(
  1067. rf"<{tag}(.*?)>(.|\n)*?</{tag}>",
  1068. "",
  1069. content,
  1070. flags=re.DOTALL,
  1071. )
  1072. return content, content_blocks, end_flag
  1073. message = Chats.get_message_by_id_and_message_id(
  1074. metadata["chat_id"], metadata["message_id"]
  1075. )
  1076. tool_calls = []
  1077. content = message.get("content", "") if message else ""
  1078. content_blocks = [
  1079. {
  1080. "type": "text",
  1081. "content": content,
  1082. }
  1083. ]
  1084. # We might want to disable this by default
  1085. DETECT_REASONING = True
  1086. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1087. "code_interpreter", False
  1088. )
  1089. reasoning_tags = [
  1090. "think",
  1091. "thinking",
  1092. "reason",
  1093. "reasoning",
  1094. "thought",
  1095. "Thought",
  1096. ]
  1097. code_interpreter_tags = ["code_interpreter"]
  1098. try:
  1099. for event in events:
  1100. await event_emitter(
  1101. {
  1102. "type": "chat:completion",
  1103. "data": event,
  1104. }
  1105. )
  1106. # Save message in the database
  1107. Chats.upsert_message_to_chat_by_id_and_message_id(
  1108. metadata["chat_id"],
  1109. metadata["message_id"],
  1110. {
  1111. **event,
  1112. },
  1113. )
  1114. async def stream_body_handler(response):
  1115. nonlocal content
  1116. nonlocal content_blocks
  1117. response_tool_calls = []
  1118. async for line in response.body_iterator:
  1119. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1120. data = line
  1121. # Skip empty lines
  1122. if not data.strip():
  1123. continue
  1124. # "data:" is the prefix for each event
  1125. if not data.startswith("data:"):
  1126. continue
  1127. # Remove the prefix
  1128. data = data[len("data:") :].strip()
  1129. try:
  1130. data = json.loads(data)
  1131. if "selected_model_id" in data:
  1132. model_id = data["selected_model_id"]
  1133. Chats.upsert_message_to_chat_by_id_and_message_id(
  1134. metadata["chat_id"],
  1135. metadata["message_id"],
  1136. {
  1137. "selectedModelId": model_id,
  1138. },
  1139. )
  1140. else:
  1141. choices = data.get("choices", [])
  1142. if not choices:
  1143. continue
  1144. delta = choices[0].get("delta", {})
  1145. delta_tool_calls = delta.get("tool_calls", None)
  1146. if delta_tool_calls:
  1147. for delta_tool_call in delta_tool_calls:
  1148. tool_call_index = delta_tool_call.get("index")
  1149. if tool_call_index is not None:
  1150. if (
  1151. len(response_tool_calls)
  1152. <= tool_call_index
  1153. ):
  1154. response_tool_calls.append(
  1155. delta_tool_call
  1156. )
  1157. else:
  1158. delta_name = delta_tool_call.get(
  1159. "function", {}
  1160. ).get("name")
  1161. delta_arguments = delta_tool_call.get(
  1162. "function", {}
  1163. ).get("arguments")
  1164. if delta_name:
  1165. response_tool_calls[
  1166. tool_call_index
  1167. ]["function"]["name"] += delta_name
  1168. if delta_arguments:
  1169. response_tool_calls[
  1170. tool_call_index
  1171. ]["function"][
  1172. "arguments"
  1173. ] += delta_arguments
  1174. value = delta.get("content")
  1175. if value:
  1176. content = f"{content}{value}"
  1177. if not content_blocks:
  1178. content_blocks.append(
  1179. {
  1180. "type": "text",
  1181. "content": "",
  1182. }
  1183. )
  1184. content_blocks[-1]["content"] = (
  1185. content_blocks[-1]["content"] + value
  1186. )
  1187. if DETECT_REASONING:
  1188. content, content_blocks, _ = (
  1189. tag_content_handler(
  1190. "reasoning",
  1191. reasoning_tags,
  1192. content,
  1193. content_blocks,
  1194. )
  1195. )
  1196. if DETECT_CODE_INTERPRETER:
  1197. content, content_blocks, end = (
  1198. tag_content_handler(
  1199. "code_interpreter",
  1200. code_interpreter_tags,
  1201. content,
  1202. content_blocks,
  1203. )
  1204. )
  1205. if end:
  1206. break
  1207. if ENABLE_REALTIME_CHAT_SAVE:
  1208. # Save message in the database
  1209. Chats.upsert_message_to_chat_by_id_and_message_id(
  1210. metadata["chat_id"],
  1211. metadata["message_id"],
  1212. {
  1213. "content": serialize_content_blocks(
  1214. content_blocks
  1215. ),
  1216. },
  1217. )
  1218. else:
  1219. data = {
  1220. "content": serialize_content_blocks(
  1221. content_blocks
  1222. ),
  1223. }
  1224. await event_emitter(
  1225. {
  1226. "type": "chat:completion",
  1227. "data": data,
  1228. }
  1229. )
  1230. except Exception as e:
  1231. done = "data: [DONE]" in line
  1232. if done:
  1233. pass
  1234. else:
  1235. log.debug("Error: ", e)
  1236. continue
  1237. if content_blocks:
  1238. # Clean up the last text block
  1239. if content_blocks[-1]["type"] == "text":
  1240. content_blocks[-1]["content"] = content_blocks[-1][
  1241. "content"
  1242. ].strip()
  1243. if not content_blocks[-1]["content"]:
  1244. content_blocks.pop()
  1245. if not content_blocks:
  1246. content_blocks.append(
  1247. {
  1248. "type": "text",
  1249. "content": "",
  1250. }
  1251. )
  1252. if response_tool_calls:
  1253. tool_calls.append(response_tool_calls)
  1254. if response.background:
  1255. await response.background()
  1256. await stream_body_handler(response)
  1257. MAX_TOOL_CALL_RETRIES = 5
  1258. tool_call_retries = 0
  1259. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1260. tool_call_retries += 1
  1261. response_tool_calls = tool_calls.pop(0)
  1262. content_blocks.append(
  1263. {
  1264. "type": "tool_calls",
  1265. "content": response_tool_calls,
  1266. }
  1267. )
  1268. await event_emitter(
  1269. {
  1270. "type": "chat:completion",
  1271. "data": {
  1272. "content": serialize_content_blocks(content_blocks),
  1273. },
  1274. }
  1275. )
  1276. tools = metadata.get("tools", {})
  1277. results = []
  1278. for tool_call in response_tool_calls:
  1279. print("\n\n" + str(tool_call) + "\n\n")
  1280. tool_call_id = tool_call.get("id", "")
  1281. tool_name = tool_call.get("function", {}).get("name", "")
  1282. tool_function_params = {}
  1283. try:
  1284. # json.loads cannot be used because some models do not produce valid JSON
  1285. tool_function_params = ast.literal_eval(
  1286. tool_call.get("function", {}).get("arguments", "{}")
  1287. )
  1288. except Exception as e:
  1289. log.debug(e)
  1290. tool_result = None
  1291. if tool_name in tools:
  1292. tool = tools[tool_name]
  1293. spec = tool.get("spec", {})
  1294. try:
  1295. required_params = spec.get("parameters", {}).get(
  1296. "required", []
  1297. )
  1298. tool_function = tool["callable"]
  1299. tool_function_params = {
  1300. k: v
  1301. for k, v in tool_function_params.items()
  1302. if k in required_params
  1303. }
  1304. tool_result = await tool_function(
  1305. **tool_function_params
  1306. )
  1307. except Exception as e:
  1308. tool_result = str(e)
  1309. results.append(
  1310. {
  1311. "tool_call_id": tool_call_id,
  1312. "content": tool_result,
  1313. }
  1314. )
  1315. content_blocks[-1]["results"] = results
  1316. content_blocks.append(
  1317. {
  1318. "type": "text",
  1319. "content": "",
  1320. }
  1321. )
  1322. await event_emitter(
  1323. {
  1324. "type": "chat:completion",
  1325. "data": {
  1326. "content": serialize_content_blocks(content_blocks),
  1327. },
  1328. }
  1329. )
  1330. try:
  1331. res = await generate_chat_completion(
  1332. request,
  1333. {
  1334. "model": model_id,
  1335. "stream": True,
  1336. "messages": [
  1337. *form_data["messages"],
  1338. {
  1339. "role": "assistant",
  1340. "content": serialize_content_blocks(
  1341. content_blocks, raw=True
  1342. ),
  1343. "tool_calls": response_tool_calls,
  1344. },
  1345. *[
  1346. {
  1347. "role": "tool",
  1348. "tool_call_id": result["tool_call_id"],
  1349. "content": result["content"],
  1350. }
  1351. for result in results
  1352. ],
  1353. ],
  1354. },
  1355. user,
  1356. )
  1357. if isinstance(res, StreamingResponse):
  1358. await stream_body_handler(res)
  1359. else:
  1360. break
  1361. except Exception as e:
  1362. log.debug(e)
  1363. break
  1364. if DETECT_CODE_INTERPRETER:
  1365. MAX_RETRIES = 5
  1366. retries = 0
  1367. while (
  1368. content_blocks[-1]["type"] == "code_interpreter"
  1369. and retries < MAX_RETRIES
  1370. ):
  1371. retries += 1
  1372. log.debug(f"Attempt count: {retries}")
  1373. output = ""
  1374. try:
  1375. if content_blocks[-1]["attributes"].get("type") == "code":
  1376. output = await event_caller(
  1377. {
  1378. "type": "execute:python",
  1379. "data": {
  1380. "id": str(uuid4()),
  1381. "code": content_blocks[-1]["content"],
  1382. },
  1383. }
  1384. )
  1385. if isinstance(output, dict):
  1386. stdout = output.get("stdout", "")
  1387. if stdout:
  1388. stdoutLines = stdout.split("\n")
  1389. for idx, line in enumerate(stdoutLines):
  1390. if "data:image/png;base64" in line:
  1391. id = str(uuid4())
  1392. # ensure the path exists
  1393. os.makedirs(
  1394. os.path.join(CACHE_DIR, "images"),
  1395. exist_ok=True,
  1396. )
  1397. image_path = os.path.join(
  1398. CACHE_DIR,
  1399. f"images/{id}.png",
  1400. )
  1401. with open(image_path, "wb") as f:
  1402. f.write(
  1403. base64.b64decode(
  1404. line.split(",")[1]
  1405. )
  1406. )
  1407. stdoutLines[idx] = (
  1408. f"![Output Image {idx}](/cache/images/{id}.png)"
  1409. )
  1410. output["stdout"] = "\n".join(stdoutLines)
  1411. except Exception as e:
  1412. output = str(e)
  1413. content_blocks[-1]["output"] = output
  1414. content_blocks.append(
  1415. {
  1416. "type": "text",
  1417. "content": "",
  1418. }
  1419. )
  1420. await event_emitter(
  1421. {
  1422. "type": "chat:completion",
  1423. "data": {
  1424. "content": serialize_content_blocks(content_blocks),
  1425. },
  1426. }
  1427. )
  1428. try:
  1429. res = await generate_chat_completion(
  1430. request,
  1431. {
  1432. "model": model_id,
  1433. "stream": True,
  1434. "messages": [
  1435. *form_data["messages"],
  1436. {
  1437. "role": "assistant",
  1438. "content": serialize_content_blocks(
  1439. content_blocks, raw=True
  1440. ),
  1441. },
  1442. ],
  1443. },
  1444. user,
  1445. )
  1446. if isinstance(res, StreamingResponse):
  1447. await stream_body_handler(res)
  1448. else:
  1449. break
  1450. except Exception as e:
  1451. log.debug(e)
  1452. break
  1453. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1454. data = {
  1455. "done": True,
  1456. "content": serialize_content_blocks(content_blocks),
  1457. "title": title,
  1458. }
  1459. if not ENABLE_REALTIME_CHAT_SAVE:
  1460. # Save message in the database
  1461. Chats.upsert_message_to_chat_by_id_and_message_id(
  1462. metadata["chat_id"],
  1463. metadata["message_id"],
  1464. {
  1465. "content": serialize_content_blocks(content_blocks),
  1466. },
  1467. )
  1468. # Send a webhook notification if the user is not active
  1469. if get_active_status_by_user_id(user.id) is None:
  1470. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1471. if webhook_url:
  1472. post_webhook(
  1473. webhook_url,
  1474. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1475. {
  1476. "action": "chat",
  1477. "message": content,
  1478. "title": title,
  1479. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1480. },
  1481. )
  1482. await event_emitter(
  1483. {
  1484. "type": "chat:completion",
  1485. "data": data,
  1486. }
  1487. )
  1488. await background_tasks_handler()
  1489. except asyncio.CancelledError:
  1490. print("Task was cancelled!")
  1491. await event_emitter({"type": "task-cancelled"})
  1492. if not ENABLE_REALTIME_CHAT_SAVE:
  1493. # Save message in the database
  1494. Chats.upsert_message_to_chat_by_id_and_message_id(
  1495. metadata["chat_id"],
  1496. metadata["message_id"],
  1497. {
  1498. "content": serialize_content_blocks(content_blocks),
  1499. },
  1500. )
  1501. if response.background is not None:
  1502. await response.background()
  1503. # background_tasks.add_task(post_response_handler, response, events)
  1504. task_id, _ = create_task(post_response_handler(response, events))
  1505. return {"status": True, "task_id": task_id}
  1506. else:
  1507. # Fallback to the original response
  1508. async def stream_wrapper(original_generator, events):
  1509. def wrap_item(item):
  1510. return f"data: {item}\n\n"
  1511. for event in events:
  1512. yield wrap_item(json.dumps(event))
  1513. async for data in original_generator:
  1514. yield data
  1515. return StreamingResponse(
  1516. stream_wrapper(response.body_iterator, events),
  1517. headers=dict(response.headers),
  1518. background=response.background,
  1519. )