middleware.py 74 KB

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