middleware.py 92 KB

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