middleware.py 82 KB

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