middleware.py 90 KB

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