middleware.py 88 KB

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