middleware.py 82 KB

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