middleware.py 72 KB

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