middleware.py 75 KB

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