middleware.py 92 KB

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