middleware.py 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470
  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("owned_by") == "ollama":
  589. # Ollama specific parameters
  590. form_data["options"] = params
  591. else:
  592. if isinstance(params, dict):
  593. for key, value in params.items():
  594. if value is not None:
  595. form_data[key] = value
  596. if "logit_bias" in params and params["logit_bias"] is not None:
  597. try:
  598. form_data["logit_bias"] = json.loads(
  599. convert_logit_bias_input_to_json(params["logit_bias"])
  600. )
  601. except Exception as e:
  602. log.exception(f"Error parsing logit_bias: {e}")
  603. return form_data
  604. async def process_chat_payload(request, form_data, user, metadata, model):
  605. form_data = apply_params_to_form_data(form_data, model)
  606. log.debug(f"form_data: {form_data}")
  607. event_emitter = get_event_emitter(metadata)
  608. event_call = get_event_call(metadata)
  609. extra_params = {
  610. "__event_emitter__": event_emitter,
  611. "__event_call__": event_call,
  612. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  613. "__metadata__": metadata,
  614. "__request__": request,
  615. "__model__": model,
  616. }
  617. # Initialize events to store additional event to be sent to the client
  618. # Initialize contexts and citation
  619. if getattr(request.state, "direct", False) and hasattr(request.state, "model"):
  620. models = {
  621. request.state.model["id"]: request.state.model,
  622. }
  623. else:
  624. models = request.app.state.MODELS
  625. task_model_id = get_task_model_id(
  626. form_data["model"],
  627. request.app.state.config.TASK_MODEL,
  628. request.app.state.config.TASK_MODEL_EXTERNAL,
  629. models,
  630. )
  631. events = []
  632. sources = []
  633. user_message = get_last_user_message(form_data["messages"])
  634. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  635. if model_knowledge:
  636. await event_emitter(
  637. {
  638. "type": "status",
  639. "data": {
  640. "action": "knowledge_search",
  641. "query": user_message,
  642. "done": False,
  643. },
  644. }
  645. )
  646. knowledge_files = []
  647. for item in model_knowledge:
  648. if item.get("collection_name"):
  649. knowledge_files.append(
  650. {
  651. "id": item.get("collection_name"),
  652. "name": item.get("name"),
  653. "legacy": True,
  654. }
  655. )
  656. elif item.get("collection_names"):
  657. knowledge_files.append(
  658. {
  659. "name": item.get("name"),
  660. "type": "collection",
  661. "collection_names": item.get("collection_names"),
  662. "legacy": True,
  663. }
  664. )
  665. else:
  666. knowledge_files.append(item)
  667. files = form_data.get("files", [])
  668. files.extend(knowledge_files)
  669. form_data["files"] = files
  670. variables = form_data.pop("variables", None)
  671. # Process the form_data through the pipeline
  672. try:
  673. form_data = await process_pipeline_inlet_filter(
  674. request, form_data, user, models
  675. )
  676. except Exception as e:
  677. raise e
  678. try:
  679. filter_functions = [
  680. Functions.get_function_by_id(filter_id)
  681. for filter_id in get_sorted_filter_ids(
  682. request, model, metadata.get("filter_ids", [])
  683. )
  684. ]
  685. form_data, flags = await process_filter_functions(
  686. request=request,
  687. filter_functions=filter_functions,
  688. filter_type="inlet",
  689. form_data=form_data,
  690. extra_params=extra_params,
  691. )
  692. except Exception as e:
  693. raise Exception(f"Error: {e}")
  694. features = form_data.pop("features", None)
  695. if features:
  696. if "memory" in features and features["memory"]:
  697. form_data = await chat_memory_handler(
  698. request, form_data, extra_params, user
  699. )
  700. if "web_search" in features and features["web_search"]:
  701. form_data = await chat_web_search_handler(
  702. request, form_data, extra_params, user
  703. )
  704. if "image_generation" in features and features["image_generation"]:
  705. form_data = await chat_image_generation_handler(
  706. request, form_data, extra_params, user
  707. )
  708. if "code_interpreter" in features and features["code_interpreter"]:
  709. form_data["messages"] = add_or_update_user_message(
  710. (
  711. request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE
  712. if request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE != ""
  713. else DEFAULT_CODE_INTERPRETER_PROMPT
  714. ),
  715. form_data["messages"],
  716. )
  717. tool_ids = form_data.pop("tool_ids", None)
  718. files = form_data.pop("files", None)
  719. # Remove files duplicates
  720. if files:
  721. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  722. metadata = {
  723. **metadata,
  724. "tool_ids": tool_ids,
  725. "files": files,
  726. }
  727. form_data["metadata"] = metadata
  728. # Server side tools
  729. tool_ids = metadata.get("tool_ids", None)
  730. # Client side tools
  731. tool_servers = metadata.get("tool_servers", None)
  732. log.debug(f"{tool_ids=}")
  733. log.debug(f"{tool_servers=}")
  734. tools_dict = {}
  735. if tool_ids:
  736. tools_dict = get_tools(
  737. request,
  738. tool_ids,
  739. user,
  740. {
  741. **extra_params,
  742. "__model__": models[task_model_id],
  743. "__messages__": form_data["messages"],
  744. "__files__": metadata.get("files", []),
  745. },
  746. )
  747. if tool_servers:
  748. for tool_server in tool_servers:
  749. tool_specs = tool_server.pop("specs", [])
  750. for tool in tool_specs:
  751. tools_dict[tool["name"]] = {
  752. "spec": tool,
  753. "direct": True,
  754. "server": tool_server,
  755. }
  756. if tools_dict:
  757. if metadata.get("function_calling") == "native":
  758. # If the function calling is native, then call the tools function calling handler
  759. metadata["tools"] = tools_dict
  760. form_data["tools"] = [
  761. {"type": "function", "function": tool.get("spec", {})}
  762. for tool in tools_dict.values()
  763. ]
  764. else:
  765. # If the function calling is not native, then call the tools function calling handler
  766. try:
  767. form_data, flags = await chat_completion_tools_handler(
  768. request, form_data, extra_params, user, models, tools_dict
  769. )
  770. sources.extend(flags.get("sources", []))
  771. except Exception as e:
  772. log.exception(e)
  773. try:
  774. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  775. sources.extend(flags.get("sources", []))
  776. except Exception as e:
  777. log.exception(e)
  778. # If context is not empty, insert it into the messages
  779. if len(sources) > 0:
  780. context_string = ""
  781. citation_idx = {}
  782. for source in sources:
  783. if "document" in source:
  784. for doc_context, doc_meta in zip(
  785. source["document"], source["metadata"]
  786. ):
  787. source_name = source.get("source", {}).get("name", None)
  788. citation_id = (
  789. doc_meta.get("source", None)
  790. or source.get("source", {}).get("id", None)
  791. or "N/A"
  792. )
  793. if citation_id not in citation_idx:
  794. citation_idx[citation_id] = len(citation_idx) + 1
  795. context_string += (
  796. f'<source id="{citation_idx[citation_id]}"'
  797. + (f' name="{source_name}"' if source_name else "")
  798. + f">{doc_context}</source>\n"
  799. )
  800. context_string = context_string.strip()
  801. prompt = get_last_user_message(form_data["messages"])
  802. if prompt is None:
  803. raise Exception("No user message found")
  804. if (
  805. request.app.state.config.RELEVANCE_THRESHOLD == 0
  806. and context_string.strip() == ""
  807. ):
  808. log.debug(
  809. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  810. )
  811. # Workaround for Ollama 2.0+ system prompt issue
  812. # TODO: replace with add_or_update_system_message
  813. if model.get("owned_by") == "ollama":
  814. form_data["messages"] = prepend_to_first_user_message_content(
  815. rag_template(
  816. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  817. ),
  818. form_data["messages"],
  819. )
  820. else:
  821. form_data["messages"] = add_or_update_system_message(
  822. rag_template(
  823. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  824. ),
  825. form_data["messages"],
  826. )
  827. # If there are citations, add them to the data_items
  828. sources = [
  829. source
  830. for source in sources
  831. if source.get("source", {}).get("name", "")
  832. or source.get("source", {}).get("id", "")
  833. ]
  834. if len(sources) > 0:
  835. events.append({"sources": sources})
  836. if model_knowledge:
  837. await event_emitter(
  838. {
  839. "type": "status",
  840. "data": {
  841. "action": "knowledge_search",
  842. "query": user_message,
  843. "done": True,
  844. "hidden": True,
  845. },
  846. }
  847. )
  848. return form_data, metadata, events
  849. async def process_chat_response(
  850. request, response, form_data, user, metadata, model, events, tasks
  851. ):
  852. async def background_tasks_handler():
  853. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  854. message = message_map.get(metadata["message_id"]) if message_map else None
  855. if message:
  856. message_list = get_message_list(message_map, metadata["message_id"])
  857. # Remove details tags and files from the messages.
  858. # as get_message_list creates a new list, it does not affect
  859. # the original messages outside of this handler
  860. messages = []
  861. for message in message_list:
  862. content = message.get("content", "")
  863. if isinstance(content, list):
  864. for item in content:
  865. if item.get("type") == "text":
  866. content = item["text"]
  867. break
  868. if isinstance(content, str):
  869. content = re.sub(
  870. r"<details\b[^>]*>.*?<\/details>|!\[.*?\]\(.*?\)",
  871. "",
  872. content,
  873. flags=re.S | re.I,
  874. ).strip()
  875. messages.append(
  876. {
  877. **message,
  878. "role": message.get(
  879. "role", "assistant"
  880. ), # Safe fallback for missing role
  881. "content": content,
  882. }
  883. )
  884. if tasks and messages:
  885. if (
  886. TASKS.FOLLOW_UP_GENERATION in tasks
  887. and tasks[TASKS.FOLLOW_UP_GENERATION]
  888. ):
  889. res = await generate_follow_ups(
  890. request,
  891. {
  892. "model": message["model"],
  893. "messages": messages,
  894. "message_id": metadata["message_id"],
  895. "chat_id": metadata["chat_id"],
  896. },
  897. user,
  898. )
  899. if res and isinstance(res, dict):
  900. if len(res.get("choices", [])) == 1:
  901. follow_ups_string = (
  902. res.get("choices", [])[0]
  903. .get("message", {})
  904. .get("content", "")
  905. )
  906. else:
  907. follow_ups_string = ""
  908. follow_ups_string = follow_ups_string[
  909. follow_ups_string.find("{") : follow_ups_string.rfind("}")
  910. + 1
  911. ]
  912. try:
  913. follow_ups = json.loads(follow_ups_string).get(
  914. "follow_ups", []
  915. )
  916. Chats.upsert_message_to_chat_by_id_and_message_id(
  917. metadata["chat_id"],
  918. metadata["message_id"],
  919. {
  920. "followUps": follow_ups,
  921. },
  922. )
  923. await event_emitter(
  924. {
  925. "type": "chat:message:follow_ups",
  926. "data": {
  927. "follow_ups": follow_ups,
  928. },
  929. }
  930. )
  931. except Exception as e:
  932. pass
  933. if TASKS.TITLE_GENERATION in tasks:
  934. user_message = get_last_user_message(messages)
  935. if user_message and len(user_message) > 100:
  936. user_message = user_message[:100] + "..."
  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(
  953. "content", message.get("content", user_message)
  954. )
  955. )
  956. else:
  957. title_string = ""
  958. title_string = title_string[
  959. title_string.find("{") : title_string.rfind("}") + 1
  960. ]
  961. try:
  962. title = json.loads(title_string).get(
  963. "title", user_message
  964. )
  965. except Exception as e:
  966. title = ""
  967. if not title:
  968. title = messages[0].get("content", user_message)
  969. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  970. await event_emitter(
  971. {
  972. "type": "chat:title",
  973. "data": title,
  974. }
  975. )
  976. elif len(messages) == 2:
  977. title = messages[0].get("content", user_message)
  978. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  979. await event_emitter(
  980. {
  981. "type": "chat:title",
  982. "data": message.get("content", user_message),
  983. }
  984. )
  985. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  986. res = await generate_chat_tags(
  987. request,
  988. {
  989. "model": message["model"],
  990. "messages": messages,
  991. "chat_id": metadata["chat_id"],
  992. },
  993. user,
  994. )
  995. if res and isinstance(res, dict):
  996. if len(res.get("choices", [])) == 1:
  997. tags_string = (
  998. res.get("choices", [])[0]
  999. .get("message", {})
  1000. .get("content", "")
  1001. )
  1002. else:
  1003. tags_string = ""
  1004. tags_string = tags_string[
  1005. tags_string.find("{") : tags_string.rfind("}") + 1
  1006. ]
  1007. try:
  1008. tags = json.loads(tags_string).get("tags", [])
  1009. Chats.update_chat_tags_by_id(
  1010. metadata["chat_id"], tags, user
  1011. )
  1012. await event_emitter(
  1013. {
  1014. "type": "chat:tags",
  1015. "data": tags,
  1016. }
  1017. )
  1018. except Exception as e:
  1019. pass
  1020. event_emitter = None
  1021. event_caller = None
  1022. if (
  1023. "session_id" in metadata
  1024. and metadata["session_id"]
  1025. and "chat_id" in metadata
  1026. and metadata["chat_id"]
  1027. and "message_id" in metadata
  1028. and metadata["message_id"]
  1029. ):
  1030. event_emitter = get_event_emitter(metadata)
  1031. event_caller = get_event_call(metadata)
  1032. # Non-streaming response
  1033. if not isinstance(response, StreamingResponse):
  1034. if event_emitter:
  1035. if "error" in response:
  1036. error = response["error"].get("detail", response["error"])
  1037. Chats.upsert_message_to_chat_by_id_and_message_id(
  1038. metadata["chat_id"],
  1039. metadata["message_id"],
  1040. {
  1041. "error": {"content": error},
  1042. },
  1043. )
  1044. if "selected_model_id" in response:
  1045. Chats.upsert_message_to_chat_by_id_and_message_id(
  1046. metadata["chat_id"],
  1047. metadata["message_id"],
  1048. {
  1049. "selectedModelId": response["selected_model_id"],
  1050. },
  1051. )
  1052. choices = response.get("choices", [])
  1053. if choices and choices[0].get("message", {}).get("content"):
  1054. content = response["choices"][0]["message"]["content"]
  1055. if content:
  1056. await event_emitter(
  1057. {
  1058. "type": "chat:completion",
  1059. "data": response,
  1060. }
  1061. )
  1062. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1063. await event_emitter(
  1064. {
  1065. "type": "chat:completion",
  1066. "data": {
  1067. "done": True,
  1068. "content": content,
  1069. "title": title,
  1070. },
  1071. }
  1072. )
  1073. # Save message in the database
  1074. Chats.upsert_message_to_chat_by_id_and_message_id(
  1075. metadata["chat_id"],
  1076. metadata["message_id"],
  1077. {
  1078. "role": "assistant",
  1079. "content": content,
  1080. },
  1081. )
  1082. # Send a webhook notification if the user is not active
  1083. if not get_active_status_by_user_id(user.id):
  1084. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1085. if webhook_url:
  1086. post_webhook(
  1087. request.app.state.WEBUI_NAME,
  1088. webhook_url,
  1089. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1090. {
  1091. "action": "chat",
  1092. "message": content,
  1093. "title": title,
  1094. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1095. },
  1096. )
  1097. await background_tasks_handler()
  1098. if events and isinstance(events, list) and isinstance(response, dict):
  1099. extra_response = {}
  1100. for event in events:
  1101. if isinstance(event, dict):
  1102. extra_response.update(event)
  1103. else:
  1104. extra_response[event] = True
  1105. response = {
  1106. **extra_response,
  1107. **response,
  1108. }
  1109. return response
  1110. else:
  1111. if events and isinstance(events, list) and isinstance(response, dict):
  1112. extra_response = {}
  1113. for event in events:
  1114. if isinstance(event, dict):
  1115. extra_response.update(event)
  1116. else:
  1117. extra_response[event] = True
  1118. response = {
  1119. **extra_response,
  1120. **response,
  1121. }
  1122. return response
  1123. # Non standard response
  1124. if not any(
  1125. content_type in response.headers["Content-Type"]
  1126. for content_type in ["text/event-stream", "application/x-ndjson"]
  1127. ):
  1128. return response
  1129. extra_params = {
  1130. "__event_emitter__": event_emitter,
  1131. "__event_call__": event_caller,
  1132. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  1133. "__metadata__": metadata,
  1134. "__request__": request,
  1135. "__model__": model,
  1136. }
  1137. filter_functions = [
  1138. Functions.get_function_by_id(filter_id)
  1139. for filter_id in get_sorted_filter_ids(
  1140. request, model, metadata.get("filter_ids", [])
  1141. )
  1142. ]
  1143. # Streaming response
  1144. if event_emitter and event_caller:
  1145. task_id = str(uuid4()) # Create a unique task ID.
  1146. model_id = form_data.get("model", "")
  1147. Chats.upsert_message_to_chat_by_id_and_message_id(
  1148. metadata["chat_id"],
  1149. metadata["message_id"],
  1150. {
  1151. "model": model_id,
  1152. },
  1153. )
  1154. def split_content_and_whitespace(content):
  1155. content_stripped = content.rstrip()
  1156. original_whitespace = (
  1157. content[len(content_stripped) :]
  1158. if len(content) > len(content_stripped)
  1159. else ""
  1160. )
  1161. return content_stripped, original_whitespace
  1162. def is_opening_code_block(content):
  1163. backtick_segments = content.split("```")
  1164. # Even number of segments means the last backticks are opening a new block
  1165. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  1166. # Handle as a background task
  1167. async def post_response_handler(response, events):
  1168. def serialize_content_blocks(content_blocks, raw=False):
  1169. content = ""
  1170. for block in content_blocks:
  1171. if block["type"] == "text":
  1172. content = f"{content}{block['content'].strip()}\n"
  1173. elif block["type"] == "tool_calls":
  1174. attributes = block.get("attributes", {})
  1175. tool_calls = block.get("content", [])
  1176. results = block.get("results", [])
  1177. if results:
  1178. tool_calls_display_content = ""
  1179. for tool_call in tool_calls:
  1180. tool_call_id = tool_call.get("id", "")
  1181. tool_name = tool_call.get("function", {}).get(
  1182. "name", ""
  1183. )
  1184. tool_arguments = tool_call.get("function", {}).get(
  1185. "arguments", ""
  1186. )
  1187. tool_result = None
  1188. tool_result_files = None
  1189. for result in results:
  1190. if tool_call_id == result.get("tool_call_id", ""):
  1191. tool_result = result.get("content", None)
  1192. tool_result_files = result.get("files", None)
  1193. break
  1194. if tool_result:
  1195. 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'
  1196. else:
  1197. 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>'
  1198. if not raw:
  1199. content = f"{content}\n{tool_calls_display_content}\n\n"
  1200. else:
  1201. tool_calls_display_content = ""
  1202. for tool_call in tool_calls:
  1203. tool_call_id = tool_call.get("id", "")
  1204. tool_name = tool_call.get("function", {}).get(
  1205. "name", ""
  1206. )
  1207. tool_arguments = tool_call.get("function", {}).get(
  1208. "arguments", ""
  1209. )
  1210. 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>'
  1211. if not raw:
  1212. content = f"{content}\n{tool_calls_display_content}\n\n"
  1213. elif block["type"] == "reasoning":
  1214. reasoning_display_content = "\n".join(
  1215. (f"> {line}" if not line.startswith(">") else line)
  1216. for line in block["content"].splitlines()
  1217. )
  1218. reasoning_duration = block.get("duration", None)
  1219. if reasoning_duration is not None:
  1220. if raw:
  1221. content = f'{content}\n<{block["start_tag"]}>{block["content"]}<{block["end_tag"]}>\n'
  1222. else:
  1223. 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'
  1224. else:
  1225. if raw:
  1226. content = f'{content}\n<{block["start_tag"]}>{block["content"]}<{block["end_tag"]}>\n'
  1227. else:
  1228. content = f'{content}\n<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1229. elif block["type"] == "code_interpreter":
  1230. attributes = block.get("attributes", {})
  1231. output = block.get("output", None)
  1232. lang = attributes.get("lang", "")
  1233. content_stripped, original_whitespace = (
  1234. split_content_and_whitespace(content)
  1235. )
  1236. if is_opening_code_block(content_stripped):
  1237. # Remove trailing backticks that would open a new block
  1238. content = (
  1239. content_stripped.rstrip("`").rstrip()
  1240. + original_whitespace
  1241. )
  1242. else:
  1243. # Keep content as is - either closing backticks or no backticks
  1244. content = content_stripped + original_whitespace
  1245. if output:
  1246. output = html.escape(json.dumps(output))
  1247. if raw:
  1248. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1249. else:
  1250. 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'
  1251. else:
  1252. if raw:
  1253. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1254. else:
  1255. content = f'{content}\n<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1256. else:
  1257. block_content = str(block["content"]).strip()
  1258. content = f"{content}{block['type']}: {block_content}\n"
  1259. return content.strip()
  1260. def convert_content_blocks_to_messages(content_blocks):
  1261. messages = []
  1262. temp_blocks = []
  1263. for idx, block in enumerate(content_blocks):
  1264. if block["type"] == "tool_calls":
  1265. messages.append(
  1266. {
  1267. "role": "assistant",
  1268. "content": serialize_content_blocks(temp_blocks),
  1269. "tool_calls": block.get("content"),
  1270. }
  1271. )
  1272. results = block.get("results", [])
  1273. for result in results:
  1274. messages.append(
  1275. {
  1276. "role": "tool",
  1277. "tool_call_id": result["tool_call_id"],
  1278. "content": result["content"],
  1279. }
  1280. )
  1281. temp_blocks = []
  1282. else:
  1283. temp_blocks.append(block)
  1284. if temp_blocks:
  1285. content = serialize_content_blocks(temp_blocks)
  1286. if content:
  1287. messages.append(
  1288. {
  1289. "role": "assistant",
  1290. "content": content,
  1291. }
  1292. )
  1293. return messages
  1294. def tag_content_handler(content_type, tags, content, content_blocks):
  1295. end_flag = False
  1296. def extract_attributes(tag_content):
  1297. """Extract attributes from a tag if they exist."""
  1298. attributes = {}
  1299. if not tag_content: # Ensure tag_content is not None
  1300. return attributes
  1301. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1302. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1303. for key, value in matches:
  1304. attributes[key] = value
  1305. return attributes
  1306. if content_blocks[-1]["type"] == "text":
  1307. for start_tag, end_tag in tags:
  1308. # Match start tag e.g., <tag> or <tag attr="value">
  1309. start_tag_pattern = rf"<{re.escape(start_tag)}(\s.*?)?>"
  1310. match = re.search(start_tag_pattern, content)
  1311. if match:
  1312. attr_content = (
  1313. match.group(1) if match.group(1) else ""
  1314. ) # Ensure it's not None
  1315. attributes = extract_attributes(
  1316. attr_content
  1317. ) # Extract attributes safely
  1318. # Capture everything before and after the matched tag
  1319. before_tag = content[
  1320. : match.start()
  1321. ] # Content before opening tag
  1322. after_tag = content[
  1323. match.end() :
  1324. ] # Content after opening tag
  1325. # Remove the start tag and after from the currently handling text block
  1326. content_blocks[-1]["content"] = content_blocks[-1][
  1327. "content"
  1328. ].replace(match.group(0) + after_tag, "")
  1329. if before_tag:
  1330. content_blocks[-1]["content"] = before_tag
  1331. if not content_blocks[-1]["content"]:
  1332. content_blocks.pop()
  1333. # Append the new block
  1334. content_blocks.append(
  1335. {
  1336. "type": content_type,
  1337. "start_tag": start_tag,
  1338. "end_tag": end_tag,
  1339. "attributes": attributes,
  1340. "content": "",
  1341. "started_at": time.time(),
  1342. }
  1343. )
  1344. if after_tag:
  1345. content_blocks[-1]["content"] = after_tag
  1346. tag_content_handler(
  1347. content_type, tags, after_tag, content_blocks
  1348. )
  1349. break
  1350. elif content_blocks[-1]["type"] == content_type:
  1351. start_tag = content_blocks[-1]["start_tag"]
  1352. end_tag = content_blocks[-1]["end_tag"]
  1353. # Match end tag e.g., </tag>
  1354. end_tag_pattern = rf"<{re.escape(end_tag)}>"
  1355. # Check if the content has the end tag
  1356. if re.search(end_tag_pattern, content):
  1357. end_flag = True
  1358. block_content = content_blocks[-1]["content"]
  1359. # Strip start and end tags from the content
  1360. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1361. block_content = re.sub(
  1362. start_tag_pattern, "", block_content
  1363. ).strip()
  1364. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1365. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1366. # Content inside the tag
  1367. block_content = (
  1368. split_content[0].strip() if split_content else ""
  1369. )
  1370. # Leftover content (everything after `</tag>`)
  1371. leftover_content = (
  1372. split_content[1].strip() if len(split_content) > 1 else ""
  1373. )
  1374. if block_content:
  1375. content_blocks[-1]["content"] = block_content
  1376. content_blocks[-1]["ended_at"] = time.time()
  1377. content_blocks[-1]["duration"] = int(
  1378. content_blocks[-1]["ended_at"]
  1379. - content_blocks[-1]["started_at"]
  1380. )
  1381. # Reset the content_blocks by appending a new text block
  1382. if content_type != "code_interpreter":
  1383. if leftover_content:
  1384. content_blocks.append(
  1385. {
  1386. "type": "text",
  1387. "content": leftover_content,
  1388. }
  1389. )
  1390. else:
  1391. content_blocks.append(
  1392. {
  1393. "type": "text",
  1394. "content": "",
  1395. }
  1396. )
  1397. else:
  1398. # Remove the block if content is empty
  1399. content_blocks.pop()
  1400. if leftover_content:
  1401. content_blocks.append(
  1402. {
  1403. "type": "text",
  1404. "content": leftover_content,
  1405. }
  1406. )
  1407. else:
  1408. content_blocks.append(
  1409. {
  1410. "type": "text",
  1411. "content": "",
  1412. }
  1413. )
  1414. # Clean processed content
  1415. content = re.sub(
  1416. rf"<{re.escape(start_tag)}(.*?)>(.|\n)*?<{re.escape(end_tag)}>",
  1417. "",
  1418. content,
  1419. flags=re.DOTALL,
  1420. )
  1421. return content, content_blocks, end_flag
  1422. message = Chats.get_message_by_id_and_message_id(
  1423. metadata["chat_id"], metadata["message_id"]
  1424. )
  1425. tool_calls = []
  1426. last_assistant_message = None
  1427. try:
  1428. if form_data["messages"][-1]["role"] == "assistant":
  1429. last_assistant_message = get_last_assistant_message(
  1430. form_data["messages"]
  1431. )
  1432. except Exception as e:
  1433. pass
  1434. content = (
  1435. message.get("content", "")
  1436. if message
  1437. else last_assistant_message if last_assistant_message else ""
  1438. )
  1439. content_blocks = [
  1440. {
  1441. "type": "text",
  1442. "content": content,
  1443. }
  1444. ]
  1445. # We might want to disable this by default
  1446. DETECT_REASONING = True
  1447. DETECT_SOLUTION = True
  1448. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1449. "code_interpreter", False
  1450. )
  1451. reasoning_tags = [
  1452. ("think", "/think"),
  1453. ("thinking", "/thinking"),
  1454. ("reason", "/reason"),
  1455. ("reasoning", "/reasoning"),
  1456. ("thought", "/thought"),
  1457. ("Thought", "/Thought"),
  1458. ("|begin_of_thought|", "|end_of_thought|"),
  1459. ]
  1460. code_interpreter_tags = [("code_interpreter", "/code_interpreter")]
  1461. solution_tags = [("|begin_of_solution|", "|end_of_solution|")]
  1462. try:
  1463. for event in events:
  1464. await event_emitter(
  1465. {
  1466. "type": "chat:completion",
  1467. "data": event,
  1468. }
  1469. )
  1470. # Save message in the database
  1471. Chats.upsert_message_to_chat_by_id_and_message_id(
  1472. metadata["chat_id"],
  1473. metadata["message_id"],
  1474. {
  1475. **event,
  1476. },
  1477. )
  1478. async def stream_body_handler(response):
  1479. nonlocal content
  1480. nonlocal content_blocks
  1481. response_tool_calls = []
  1482. async for line in response.body_iterator:
  1483. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1484. data = line
  1485. # Skip empty lines
  1486. if not data.strip():
  1487. continue
  1488. # "data:" is the prefix for each event
  1489. if not data.startswith("data:"):
  1490. continue
  1491. # Remove the prefix
  1492. data = data[len("data:") :].strip()
  1493. try:
  1494. data = json.loads(data)
  1495. data, _ = await process_filter_functions(
  1496. request=request,
  1497. filter_functions=filter_functions,
  1498. filter_type="stream",
  1499. form_data=data,
  1500. extra_params=extra_params,
  1501. )
  1502. if data:
  1503. if "event" in data:
  1504. await event_emitter(data.get("event", {}))
  1505. if "selected_model_id" in data:
  1506. model_id = data["selected_model_id"]
  1507. Chats.upsert_message_to_chat_by_id_and_message_id(
  1508. metadata["chat_id"],
  1509. metadata["message_id"],
  1510. {
  1511. "selectedModelId": model_id,
  1512. },
  1513. )
  1514. else:
  1515. choices = data.get("choices", [])
  1516. if not choices:
  1517. error = data.get("error", {})
  1518. if error:
  1519. await event_emitter(
  1520. {
  1521. "type": "chat:completion",
  1522. "data": {
  1523. "error": error,
  1524. },
  1525. }
  1526. )
  1527. usage = data.get("usage", {})
  1528. if usage:
  1529. await event_emitter(
  1530. {
  1531. "type": "chat:completion",
  1532. "data": {
  1533. "usage": usage,
  1534. },
  1535. }
  1536. )
  1537. continue
  1538. delta = choices[0].get("delta", {})
  1539. delta_tool_calls = delta.get("tool_calls", None)
  1540. if delta_tool_calls:
  1541. for delta_tool_call in delta_tool_calls:
  1542. tool_call_index = delta_tool_call.get(
  1543. "index"
  1544. )
  1545. if tool_call_index is not None:
  1546. # Check if the tool call already exists
  1547. current_response_tool_call = None
  1548. for (
  1549. response_tool_call
  1550. ) in response_tool_calls:
  1551. if (
  1552. response_tool_call.get("index")
  1553. == tool_call_index
  1554. ):
  1555. current_response_tool_call = (
  1556. response_tool_call
  1557. )
  1558. break
  1559. if current_response_tool_call is None:
  1560. # Add the new tool call
  1561. delta_tool_call.setdefault(
  1562. "function", {}
  1563. )
  1564. delta_tool_call[
  1565. "function"
  1566. ].setdefault("name", "")
  1567. delta_tool_call[
  1568. "function"
  1569. ].setdefault("arguments", "")
  1570. response_tool_calls.append(
  1571. delta_tool_call
  1572. )
  1573. else:
  1574. # Update the existing tool call
  1575. delta_name = delta_tool_call.get(
  1576. "function", {}
  1577. ).get("name")
  1578. delta_arguments = (
  1579. delta_tool_call.get(
  1580. "function", {}
  1581. ).get("arguments")
  1582. )
  1583. if delta_name:
  1584. current_response_tool_call[
  1585. "function"
  1586. ]["name"] += delta_name
  1587. if delta_arguments:
  1588. current_response_tool_call[
  1589. "function"
  1590. ][
  1591. "arguments"
  1592. ] += delta_arguments
  1593. value = delta.get("content")
  1594. reasoning_content = (
  1595. delta.get("reasoning_content")
  1596. or delta.get("reasoning")
  1597. or delta.get("thinking")
  1598. )
  1599. if reasoning_content:
  1600. if (
  1601. not content_blocks
  1602. or content_blocks[-1]["type"] != "reasoning"
  1603. ):
  1604. reasoning_block = {
  1605. "type": "reasoning",
  1606. "start_tag": "think",
  1607. "end_tag": "/think",
  1608. "attributes": {
  1609. "type": "reasoning_content"
  1610. },
  1611. "content": "",
  1612. "started_at": time.time(),
  1613. }
  1614. content_blocks.append(reasoning_block)
  1615. else:
  1616. reasoning_block = content_blocks[-1]
  1617. reasoning_block["content"] += reasoning_content
  1618. data = {
  1619. "content": serialize_content_blocks(
  1620. content_blocks
  1621. )
  1622. }
  1623. if value:
  1624. if (
  1625. content_blocks
  1626. and content_blocks[-1]["type"]
  1627. == "reasoning"
  1628. and content_blocks[-1]
  1629. .get("attributes", {})
  1630. .get("type")
  1631. == "reasoning_content"
  1632. ):
  1633. reasoning_block = content_blocks[-1]
  1634. reasoning_block["ended_at"] = time.time()
  1635. reasoning_block["duration"] = int(
  1636. reasoning_block["ended_at"]
  1637. - reasoning_block["started_at"]
  1638. )
  1639. content_blocks.append(
  1640. {
  1641. "type": "text",
  1642. "content": "",
  1643. }
  1644. )
  1645. content = f"{content}{value}"
  1646. if not content_blocks:
  1647. content_blocks.append(
  1648. {
  1649. "type": "text",
  1650. "content": "",
  1651. }
  1652. )
  1653. content_blocks[-1]["content"] = (
  1654. content_blocks[-1]["content"] + value
  1655. )
  1656. if DETECT_REASONING:
  1657. content, content_blocks, _ = (
  1658. tag_content_handler(
  1659. "reasoning",
  1660. reasoning_tags,
  1661. content,
  1662. content_blocks,
  1663. )
  1664. )
  1665. if DETECT_CODE_INTERPRETER:
  1666. content, content_blocks, end = (
  1667. tag_content_handler(
  1668. "code_interpreter",
  1669. code_interpreter_tags,
  1670. content,
  1671. content_blocks,
  1672. )
  1673. )
  1674. if end:
  1675. break
  1676. if DETECT_SOLUTION:
  1677. content, content_blocks, _ = (
  1678. tag_content_handler(
  1679. "solution",
  1680. solution_tags,
  1681. content,
  1682. content_blocks,
  1683. )
  1684. )
  1685. if ENABLE_REALTIME_CHAT_SAVE:
  1686. # Save message in the database
  1687. Chats.upsert_message_to_chat_by_id_and_message_id(
  1688. metadata["chat_id"],
  1689. metadata["message_id"],
  1690. {
  1691. "content": serialize_content_blocks(
  1692. content_blocks
  1693. ),
  1694. },
  1695. )
  1696. else:
  1697. data = {
  1698. "content": serialize_content_blocks(
  1699. content_blocks
  1700. ),
  1701. }
  1702. await event_emitter(
  1703. {
  1704. "type": "chat:completion",
  1705. "data": data,
  1706. }
  1707. )
  1708. except Exception as e:
  1709. done = "data: [DONE]" in line
  1710. if done:
  1711. pass
  1712. else:
  1713. log.debug("Error: ", e)
  1714. continue
  1715. if content_blocks:
  1716. # Clean up the last text block
  1717. if content_blocks[-1]["type"] == "text":
  1718. content_blocks[-1]["content"] = content_blocks[-1][
  1719. "content"
  1720. ].strip()
  1721. if not content_blocks[-1]["content"]:
  1722. content_blocks.pop()
  1723. if not content_blocks:
  1724. content_blocks.append(
  1725. {
  1726. "type": "text",
  1727. "content": "",
  1728. }
  1729. )
  1730. if response_tool_calls:
  1731. tool_calls.append(response_tool_calls)
  1732. if response.background:
  1733. await response.background()
  1734. await stream_body_handler(response)
  1735. MAX_TOOL_CALL_RETRIES = 10
  1736. tool_call_retries = 0
  1737. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1738. tool_call_retries += 1
  1739. response_tool_calls = tool_calls.pop(0)
  1740. content_blocks.append(
  1741. {
  1742. "type": "tool_calls",
  1743. "content": response_tool_calls,
  1744. }
  1745. )
  1746. await event_emitter(
  1747. {
  1748. "type": "chat:completion",
  1749. "data": {
  1750. "content": serialize_content_blocks(content_blocks),
  1751. },
  1752. }
  1753. )
  1754. tools = metadata.get("tools", {})
  1755. results = []
  1756. for tool_call in response_tool_calls:
  1757. tool_call_id = tool_call.get("id", "")
  1758. tool_name = tool_call.get("function", {}).get("name", "")
  1759. tool_args = tool_call.get("function", {}).get("arguments", "{}")
  1760. tool_function_params = {}
  1761. try:
  1762. # json.loads cannot be used because some models do not produce valid JSON
  1763. tool_function_params = ast.literal_eval(tool_args)
  1764. except Exception as e:
  1765. log.debug(e)
  1766. # Fallback to JSON parsing
  1767. try:
  1768. tool_function_params = json.loads(tool_args)
  1769. except Exception as e:
  1770. log.error(
  1771. f"Error parsing tool call arguments: {tool_args}"
  1772. )
  1773. # Mutate the original tool call response params as they are passed back to the passed
  1774. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  1775. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  1776. # params are not valid json.
  1777. # Main case so far is no args = "" = invalid json.
  1778. log.debug(
  1779. f"Parsed args from {tool_args} to {tool_function_params}"
  1780. )
  1781. tool_call.setdefault("function", {})["arguments"] = json.dumps(
  1782. tool_function_params
  1783. )
  1784. tool_result = None
  1785. if tool_name in tools:
  1786. tool = tools[tool_name]
  1787. spec = tool.get("spec", {})
  1788. try:
  1789. allowed_params = (
  1790. spec.get("parameters", {})
  1791. .get("properties", {})
  1792. .keys()
  1793. )
  1794. tool_function_params = {
  1795. k: v
  1796. for k, v in tool_function_params.items()
  1797. if k in allowed_params
  1798. }
  1799. if tool.get("direct", False):
  1800. tool_result = await event_caller(
  1801. {
  1802. "type": "execute:tool",
  1803. "data": {
  1804. "id": str(uuid4()),
  1805. "name": tool_name,
  1806. "params": tool_function_params,
  1807. "server": tool.get("server", {}),
  1808. "session_id": metadata.get(
  1809. "session_id", None
  1810. ),
  1811. },
  1812. }
  1813. )
  1814. else:
  1815. tool_function = tool["callable"]
  1816. tool_result = await tool_function(
  1817. **tool_function_params
  1818. )
  1819. except Exception as e:
  1820. tool_result = str(e)
  1821. tool_result_files = []
  1822. if isinstance(tool_result, list):
  1823. for item in tool_result:
  1824. # check if string
  1825. if isinstance(item, str) and item.startswith("data:"):
  1826. tool_result_files.append(item)
  1827. tool_result.remove(item)
  1828. if isinstance(tool_result, dict) or isinstance(
  1829. tool_result, list
  1830. ):
  1831. tool_result = json.dumps(tool_result, indent=2)
  1832. results.append(
  1833. {
  1834. "tool_call_id": tool_call_id,
  1835. "content": tool_result,
  1836. **(
  1837. {"files": tool_result_files}
  1838. if tool_result_files
  1839. else {}
  1840. ),
  1841. }
  1842. )
  1843. content_blocks[-1]["results"] = results
  1844. content_blocks.append(
  1845. {
  1846. "type": "text",
  1847. "content": "",
  1848. }
  1849. )
  1850. await event_emitter(
  1851. {
  1852. "type": "chat:completion",
  1853. "data": {
  1854. "content": serialize_content_blocks(content_blocks),
  1855. },
  1856. }
  1857. )
  1858. try:
  1859. res = await generate_chat_completion(
  1860. request,
  1861. {
  1862. "model": model_id,
  1863. "stream": True,
  1864. "tools": form_data["tools"],
  1865. "messages": [
  1866. *form_data["messages"],
  1867. *convert_content_blocks_to_messages(content_blocks),
  1868. ],
  1869. },
  1870. user,
  1871. )
  1872. if isinstance(res, StreamingResponse):
  1873. await stream_body_handler(res)
  1874. else:
  1875. break
  1876. except Exception as e:
  1877. log.debug(e)
  1878. break
  1879. if DETECT_CODE_INTERPRETER:
  1880. MAX_RETRIES = 5
  1881. retries = 0
  1882. while (
  1883. content_blocks[-1]["type"] == "code_interpreter"
  1884. and retries < MAX_RETRIES
  1885. ):
  1886. await event_emitter(
  1887. {
  1888. "type": "chat:completion",
  1889. "data": {
  1890. "content": serialize_content_blocks(content_blocks),
  1891. },
  1892. }
  1893. )
  1894. retries += 1
  1895. log.debug(f"Attempt count: {retries}")
  1896. output = ""
  1897. try:
  1898. if content_blocks[-1]["attributes"].get("type") == "code":
  1899. code = content_blocks[-1]["content"]
  1900. if (
  1901. request.app.state.config.CODE_INTERPRETER_ENGINE
  1902. == "pyodide"
  1903. ):
  1904. output = await event_caller(
  1905. {
  1906. "type": "execute:python",
  1907. "data": {
  1908. "id": str(uuid4()),
  1909. "code": code,
  1910. "session_id": metadata.get(
  1911. "session_id", None
  1912. ),
  1913. },
  1914. }
  1915. )
  1916. elif (
  1917. request.app.state.config.CODE_INTERPRETER_ENGINE
  1918. == "jupyter"
  1919. ):
  1920. output = await execute_code_jupyter(
  1921. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  1922. code,
  1923. (
  1924. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  1925. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1926. == "token"
  1927. else None
  1928. ),
  1929. (
  1930. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  1931. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1932. == "password"
  1933. else None
  1934. ),
  1935. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  1936. )
  1937. else:
  1938. output = {
  1939. "stdout": "Code interpreter engine not configured."
  1940. }
  1941. log.debug(f"Code interpreter output: {output}")
  1942. if isinstance(output, dict):
  1943. stdout = output.get("stdout", "")
  1944. if isinstance(stdout, str):
  1945. stdoutLines = stdout.split("\n")
  1946. for idx, line in enumerate(stdoutLines):
  1947. if "data:image/png;base64" in line:
  1948. image_url = ""
  1949. # Extract base64 image data from the line
  1950. image_data, content_type = (
  1951. load_b64_image_data(line)
  1952. )
  1953. if image_data is not None:
  1954. image_url = upload_image(
  1955. request,
  1956. image_data,
  1957. content_type,
  1958. metadata,
  1959. user,
  1960. )
  1961. stdoutLines[idx] = (
  1962. f"![Output Image]({image_url})"
  1963. )
  1964. output["stdout"] = "\n".join(stdoutLines)
  1965. result = output.get("result", "")
  1966. if isinstance(result, str):
  1967. resultLines = result.split("\n")
  1968. for idx, line in enumerate(resultLines):
  1969. if "data:image/png;base64" in line:
  1970. image_url = ""
  1971. # Extract base64 image data from the line
  1972. image_data, content_type = (
  1973. load_b64_image_data(line)
  1974. )
  1975. if image_data is not None:
  1976. image_url = upload_image(
  1977. request,
  1978. image_data,
  1979. content_type,
  1980. metadata,
  1981. user,
  1982. )
  1983. resultLines[idx] = (
  1984. f"![Output Image]({image_url})"
  1985. )
  1986. output["result"] = "\n".join(resultLines)
  1987. except Exception as e:
  1988. output = str(e)
  1989. content_blocks[-1]["output"] = output
  1990. content_blocks.append(
  1991. {
  1992. "type": "text",
  1993. "content": "",
  1994. }
  1995. )
  1996. await event_emitter(
  1997. {
  1998. "type": "chat:completion",
  1999. "data": {
  2000. "content": serialize_content_blocks(content_blocks),
  2001. },
  2002. }
  2003. )
  2004. try:
  2005. res = await generate_chat_completion(
  2006. request,
  2007. {
  2008. "model": model_id,
  2009. "stream": True,
  2010. "messages": [
  2011. *form_data["messages"],
  2012. {
  2013. "role": "assistant",
  2014. "content": serialize_content_blocks(
  2015. content_blocks, raw=True
  2016. ),
  2017. },
  2018. ],
  2019. },
  2020. user,
  2021. )
  2022. if isinstance(res, StreamingResponse):
  2023. await stream_body_handler(res)
  2024. else:
  2025. break
  2026. except Exception as e:
  2027. log.debug(e)
  2028. break
  2029. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  2030. data = {
  2031. "done": True,
  2032. "content": serialize_content_blocks(content_blocks),
  2033. "title": title,
  2034. }
  2035. if not ENABLE_REALTIME_CHAT_SAVE:
  2036. # Save message in the database
  2037. Chats.upsert_message_to_chat_by_id_and_message_id(
  2038. metadata["chat_id"],
  2039. metadata["message_id"],
  2040. {
  2041. "content": serialize_content_blocks(content_blocks),
  2042. },
  2043. )
  2044. # Send a webhook notification if the user is not active
  2045. if not get_active_status_by_user_id(user.id):
  2046. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  2047. if webhook_url:
  2048. post_webhook(
  2049. request.app.state.WEBUI_NAME,
  2050. webhook_url,
  2051. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  2052. {
  2053. "action": "chat",
  2054. "message": content,
  2055. "title": title,
  2056. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  2057. },
  2058. )
  2059. await event_emitter(
  2060. {
  2061. "type": "chat:completion",
  2062. "data": data,
  2063. }
  2064. )
  2065. await background_tasks_handler()
  2066. except asyncio.CancelledError:
  2067. log.warning("Task was cancelled!")
  2068. await event_emitter({"type": "task-cancelled"})
  2069. if not ENABLE_REALTIME_CHAT_SAVE:
  2070. # Save message in the database
  2071. Chats.upsert_message_to_chat_by_id_and_message_id(
  2072. metadata["chat_id"],
  2073. metadata["message_id"],
  2074. {
  2075. "content": serialize_content_blocks(content_blocks),
  2076. },
  2077. )
  2078. if response.background is not None:
  2079. await response.background()
  2080. # background_tasks.add_task(post_response_handler, response, events)
  2081. task_id, _ = await create_task(
  2082. request, post_response_handler(response, events), id=metadata["chat_id"]
  2083. )
  2084. return {"status": True, "task_id": task_id}
  2085. else:
  2086. # Fallback to the original response
  2087. async def stream_wrapper(original_generator, events):
  2088. def wrap_item(item):
  2089. return f"data: {item}\n\n"
  2090. for event in events:
  2091. event, _ = await process_filter_functions(
  2092. request=request,
  2093. filter_functions=filter_functions,
  2094. filter_type="stream",
  2095. form_data=event,
  2096. extra_params=extra_params,
  2097. )
  2098. if event:
  2099. yield wrap_item(json.dumps(event))
  2100. async for data in original_generator:
  2101. data, _ = await process_filter_functions(
  2102. request=request,
  2103. filter_functions=filter_functions,
  2104. filter_type="stream",
  2105. form_data=data,
  2106. extra_params=extra_params,
  2107. )
  2108. if data:
  2109. yield data
  2110. return StreamingResponse(
  2111. stream_wrapper(response.body_iterator, events),
  2112. headers=dict(response.headers),
  2113. background=response.background,
  2114. )