middleware.py 79 KB

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