middleware.py 74 KB

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