middleware.py 82 KB

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