middleware.py 87 KB

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