middleware.py 92 KB

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