middleware.py 92 KB

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