middleware.py 73 KB

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