middleware.py 97 KB

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