middleware.py 73 KB

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