middleware.py 95 KB

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