middleware.py 91 KB

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