middleware.py 90 KB

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