middleware.py 82 KB

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