middleware.py 84 KB

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