middleware.py 73 KB

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