middleware.py 69 KB

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