middleware.py 95 KB

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