middleware.py 92 KB

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