middleware.py 92 KB

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