middleware.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893
  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. models = request.app.state.MODELS
  516. task_model_id = get_task_model_id(
  517. form_data["model"],
  518. request.app.state.config.TASK_MODEL,
  519. request.app.state.config.TASK_MODEL_EXTERNAL,
  520. models,
  521. )
  522. events = []
  523. sources = []
  524. user_message = get_last_user_message(form_data["messages"])
  525. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  526. if model_knowledge:
  527. await event_emitter(
  528. {
  529. "type": "status",
  530. "data": {
  531. "action": "knowledge_search",
  532. "query": user_message,
  533. "done": False,
  534. },
  535. }
  536. )
  537. knowledge_files = []
  538. for item in model_knowledge:
  539. if item.get("collection_name"):
  540. knowledge_files.append(
  541. {
  542. "id": item.get("collection_name"),
  543. "name": item.get("name"),
  544. "legacy": True,
  545. }
  546. )
  547. elif item.get("collection_names"):
  548. knowledge_files.append(
  549. {
  550. "name": item.get("name"),
  551. "type": "collection",
  552. "collection_names": item.get("collection_names"),
  553. "legacy": True,
  554. }
  555. )
  556. else:
  557. knowledge_files.append(item)
  558. files = form_data.get("files", [])
  559. files.extend(knowledge_files)
  560. form_data["files"] = files
  561. variables = form_data.pop("variables", None)
  562. features = form_data.pop("features", None)
  563. if features:
  564. if "web_search" in features and features["web_search"]:
  565. form_data = await chat_web_search_handler(
  566. request, form_data, extra_params, user
  567. )
  568. if "image_generation" in features and features["image_generation"]:
  569. form_data = await chat_image_generation_handler(
  570. request, form_data, extra_params, user
  571. )
  572. if "code_interpreter" in features and features["code_interpreter"]:
  573. form_data["messages"] = add_or_update_user_message(
  574. DEFAULT_CODE_INTERPRETER_PROMPT, form_data["messages"]
  575. )
  576. try:
  577. form_data, flags = await process_filter_functions(
  578. request=request,
  579. filter_ids=get_sorted_filter_ids(model),
  580. filter_type="inlet",
  581. form_data=form_data,
  582. extra_params=extra_params,
  583. )
  584. except Exception as e:
  585. raise Exception(f"Error: {e}")
  586. tool_ids = form_data.pop("tool_ids", None)
  587. files = form_data.pop("files", None)
  588. # Remove files duplicates
  589. if files:
  590. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  591. metadata = {
  592. **metadata,
  593. "tool_ids": tool_ids,
  594. "files": files,
  595. }
  596. form_data["metadata"] = metadata
  597. tool_ids = metadata.get("tool_ids", None)
  598. log.debug(f"{tool_ids=}")
  599. if tool_ids:
  600. # If tool_ids field is present, then get the tools
  601. tools = get_tools(
  602. request,
  603. tool_ids,
  604. user,
  605. {
  606. **extra_params,
  607. "__model__": models[task_model_id],
  608. "__messages__": form_data["messages"],
  609. "__files__": metadata.get("files", []),
  610. },
  611. )
  612. log.info(f"{tools=}")
  613. if metadata.get("function_calling") == "native":
  614. # If the function calling is native, then call the tools function calling handler
  615. metadata["tools"] = tools
  616. form_data["tools"] = [
  617. {"type": "function", "function": tool.get("spec", {})}
  618. for tool in tools.values()
  619. ]
  620. else:
  621. # If the function calling is not native, then call the tools function calling handler
  622. try:
  623. form_data, flags = await chat_completion_tools_handler(
  624. request, form_data, user, models, tools
  625. )
  626. sources.extend(flags.get("sources", []))
  627. except Exception as e:
  628. log.exception(e)
  629. try:
  630. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  631. sources.extend(flags.get("sources", []))
  632. except Exception as e:
  633. log.exception(e)
  634. # If context is not empty, insert it into the messages
  635. if len(sources) > 0:
  636. context_string = ""
  637. for source_idx, source in enumerate(sources):
  638. source_id = source.get("source", {}).get("name", "")
  639. if "document" in source:
  640. for doc_idx, doc_context in enumerate(source["document"]):
  641. doc_metadata = source.get("metadata")
  642. doc_source_id = None
  643. if doc_metadata:
  644. doc_source_id = doc_metadata[doc_idx].get("source", source_id)
  645. if source_id:
  646. context_string += f"<source><source_id>{doc_source_id if doc_source_id is not None else source_id}</source_id><source_context>{doc_context}</source_context></source>\n"
  647. else:
  648. # If there is no source_id, then do not include the source_id tag
  649. context_string += f"<source><source_context>{doc_context}</source_context></source>\n"
  650. context_string = context_string.strip()
  651. prompt = get_last_user_message(form_data["messages"])
  652. if prompt is None:
  653. raise Exception("No user message found")
  654. if (
  655. request.app.state.config.RELEVANCE_THRESHOLD == 0
  656. and context_string.strip() == ""
  657. ):
  658. log.debug(
  659. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  660. )
  661. # Workaround for Ollama 2.0+ system prompt issue
  662. # TODO: replace with add_or_update_system_message
  663. if model["owned_by"] == "ollama":
  664. form_data["messages"] = prepend_to_first_user_message_content(
  665. rag_template(
  666. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  667. ),
  668. form_data["messages"],
  669. )
  670. else:
  671. form_data["messages"] = add_or_update_system_message(
  672. rag_template(
  673. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  674. ),
  675. form_data["messages"],
  676. )
  677. # If there are citations, add them to the data_items
  678. sources = [source for source in sources if source.get("source", {}).get("name", "")]
  679. if len(sources) > 0:
  680. events.append({"sources": sources})
  681. if model_knowledge:
  682. await event_emitter(
  683. {
  684. "type": "status",
  685. "data": {
  686. "action": "knowledge_search",
  687. "query": user_message,
  688. "done": True,
  689. "hidden": True,
  690. },
  691. }
  692. )
  693. return form_data, metadata, events
  694. async def process_chat_response(
  695. request, response, form_data, user, events, metadata, tasks
  696. ):
  697. async def background_tasks_handler():
  698. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  699. message = message_map.get(metadata["message_id"]) if message_map else None
  700. if message:
  701. messages = get_message_list(message_map, message.get("id"))
  702. if tasks and messages:
  703. if TASKS.TITLE_GENERATION in tasks:
  704. if tasks[TASKS.TITLE_GENERATION]:
  705. res = await generate_title(
  706. request,
  707. {
  708. "model": message["model"],
  709. "messages": messages,
  710. "chat_id": metadata["chat_id"],
  711. },
  712. user,
  713. )
  714. if res and isinstance(res, dict):
  715. if len(res.get("choices", [])) == 1:
  716. title_string = (
  717. res.get("choices", [])[0]
  718. .get("message", {})
  719. .get("content", message.get("content", "New Chat"))
  720. )
  721. else:
  722. title_string = ""
  723. title_string = title_string[
  724. title_string.find("{") : title_string.rfind("}") + 1
  725. ]
  726. try:
  727. title = json.loads(title_string).get(
  728. "title", "New Chat"
  729. )
  730. except Exception as e:
  731. title = ""
  732. if not title:
  733. title = messages[0].get("content", "New Chat")
  734. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  735. await event_emitter(
  736. {
  737. "type": "chat:title",
  738. "data": title,
  739. }
  740. )
  741. elif len(messages) == 2:
  742. title = messages[0].get("content", "New Chat")
  743. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  744. await event_emitter(
  745. {
  746. "type": "chat:title",
  747. "data": message.get("content", "New Chat"),
  748. }
  749. )
  750. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  751. res = await generate_chat_tags(
  752. request,
  753. {
  754. "model": message["model"],
  755. "messages": messages,
  756. "chat_id": metadata["chat_id"],
  757. },
  758. user,
  759. )
  760. if res and isinstance(res, dict):
  761. if len(res.get("choices", [])) == 1:
  762. tags_string = (
  763. res.get("choices", [])[0]
  764. .get("message", {})
  765. .get("content", "")
  766. )
  767. else:
  768. tags_string = ""
  769. tags_string = tags_string[
  770. tags_string.find("{") : tags_string.rfind("}") + 1
  771. ]
  772. try:
  773. tags = json.loads(tags_string).get("tags", [])
  774. Chats.update_chat_tags_by_id(
  775. metadata["chat_id"], tags, user
  776. )
  777. await event_emitter(
  778. {
  779. "type": "chat:tags",
  780. "data": tags,
  781. }
  782. )
  783. except Exception as e:
  784. pass
  785. event_emitter = None
  786. event_caller = None
  787. if (
  788. "session_id" in metadata
  789. and metadata["session_id"]
  790. and "chat_id" in metadata
  791. and metadata["chat_id"]
  792. and "message_id" in metadata
  793. and metadata["message_id"]
  794. ):
  795. event_emitter = get_event_emitter(metadata)
  796. event_caller = get_event_call(metadata)
  797. # Non-streaming response
  798. if not isinstance(response, StreamingResponse):
  799. if event_emitter:
  800. if "selected_model_id" in response:
  801. Chats.upsert_message_to_chat_by_id_and_message_id(
  802. metadata["chat_id"],
  803. metadata["message_id"],
  804. {
  805. "selectedModelId": response["selected_model_id"],
  806. },
  807. )
  808. if response.get("choices", [])[0].get("message", {}).get("content"):
  809. content = response["choices"][0]["message"]["content"]
  810. if content:
  811. await event_emitter(
  812. {
  813. "type": "chat:completion",
  814. "data": response,
  815. }
  816. )
  817. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  818. await event_emitter(
  819. {
  820. "type": "chat:completion",
  821. "data": {
  822. "done": True,
  823. "content": content,
  824. "title": title,
  825. },
  826. }
  827. )
  828. # Save message in the database
  829. Chats.upsert_message_to_chat_by_id_and_message_id(
  830. metadata["chat_id"],
  831. metadata["message_id"],
  832. {
  833. "content": content,
  834. },
  835. )
  836. # Send a webhook notification if the user is not active
  837. if get_active_status_by_user_id(user.id) is None:
  838. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  839. if webhook_url:
  840. post_webhook(
  841. webhook_url,
  842. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  843. {
  844. "action": "chat",
  845. "message": content,
  846. "title": title,
  847. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  848. },
  849. )
  850. await background_tasks_handler()
  851. return response
  852. else:
  853. return response
  854. # Non standard response
  855. if not any(
  856. content_type in response.headers["Content-Type"]
  857. for content_type in ["text/event-stream", "application/x-ndjson"]
  858. ):
  859. return response
  860. # Streaming response
  861. if event_emitter and event_caller:
  862. task_id = str(uuid4()) # Create a unique task ID.
  863. model_id = form_data.get("model", "")
  864. Chats.upsert_message_to_chat_by_id_and_message_id(
  865. metadata["chat_id"],
  866. metadata["message_id"],
  867. {
  868. "model": model_id,
  869. },
  870. )
  871. def split_content_and_whitespace(content):
  872. content_stripped = content.rstrip()
  873. original_whitespace = (
  874. content[len(content_stripped) :]
  875. if len(content) > len(content_stripped)
  876. else ""
  877. )
  878. return content_stripped, original_whitespace
  879. def is_opening_code_block(content):
  880. backtick_segments = content.split("```")
  881. # Even number of segments means the last backticks are opening a new block
  882. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  883. # Handle as a background task
  884. async def post_response_handler(response, events):
  885. def serialize_content_blocks(content_blocks, raw=False):
  886. content = ""
  887. for block in content_blocks:
  888. if block["type"] == "text":
  889. content = f"{content}{block['content'].strip()}\n"
  890. elif block["type"] == "tool_calls":
  891. attributes = block.get("attributes", {})
  892. block_content = block.get("content", [])
  893. results = block.get("results", [])
  894. if results:
  895. result_display_content = ""
  896. for result in results:
  897. tool_call_id = result.get("tool_call_id", "")
  898. tool_name = ""
  899. for tool_call in block_content:
  900. if tool_call.get("id", "") == tool_call_id:
  901. tool_name = tool_call.get("function", {}).get(
  902. "name", ""
  903. )
  904. break
  905. result_display_content = f"{result_display_content}\n> {tool_name}: {result.get('content', '')}"
  906. if not raw:
  907. 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'
  908. else:
  909. tool_calls_display_content = ""
  910. for tool_call in block_content:
  911. tool_calls_display_content = f"{tool_calls_display_content}\n> Executing {tool_call.get('function', {}).get('name', '')}"
  912. if not raw:
  913. 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'
  914. elif block["type"] == "reasoning":
  915. reasoning_display_content = "\n".join(
  916. (f"> {line}" if not line.startswith(">") else line)
  917. for line in block["content"].splitlines()
  918. )
  919. reasoning_duration = block.get("duration", None)
  920. if reasoning_duration is not None:
  921. if raw:
  922. content = f'{content}\n<{block["tag"]}>{block["content"]}</{block["tag"]}>\n'
  923. else:
  924. 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'
  925. else:
  926. if raw:
  927. content = f'{content}\n<{block["tag"]}>{block["content"]}</{block["tag"]}>\n'
  928. else:
  929. content = f'{content}\n<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  930. elif block["type"] == "code_interpreter":
  931. attributes = block.get("attributes", {})
  932. output = block.get("output", None)
  933. lang = attributes.get("lang", "")
  934. content_stripped, original_whitespace = (
  935. split_content_and_whitespace(content)
  936. )
  937. if is_opening_code_block(content_stripped):
  938. # Remove trailing backticks that would open a new block
  939. content = (
  940. content_stripped.rstrip("`").rstrip()
  941. + original_whitespace
  942. )
  943. else:
  944. # Keep content as is - either closing backticks or no backticks
  945. content = content_stripped + original_whitespace
  946. if output:
  947. output = html.escape(json.dumps(output))
  948. if raw:
  949. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  950. else:
  951. 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'
  952. else:
  953. if raw:
  954. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  955. else:
  956. content = f'{content}\n<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  957. else:
  958. block_content = str(block["content"]).strip()
  959. content = f"{content}{block['type']}: {block_content}\n"
  960. return content.strip()
  961. def tag_content_handler(content_type, tags, content, content_blocks):
  962. end_flag = False
  963. def extract_attributes(tag_content):
  964. """Extract attributes from a tag if they exist."""
  965. attributes = {}
  966. if not tag_content: # Ensure tag_content is not None
  967. return attributes
  968. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  969. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  970. for key, value in matches:
  971. attributes[key] = value
  972. return attributes
  973. if content_blocks[-1]["type"] == "text":
  974. for tag in tags:
  975. # Match start tag e.g., <tag> or <tag attr="value">
  976. start_tag_pattern = rf"<{tag}(\s.*?)?>"
  977. match = re.search(start_tag_pattern, content)
  978. if match:
  979. attr_content = (
  980. match.group(1) if match.group(1) else ""
  981. ) # Ensure it's not None
  982. attributes = extract_attributes(
  983. attr_content
  984. ) # Extract attributes safely
  985. # Capture everything before and after the matched tag
  986. before_tag = content[
  987. : match.start()
  988. ] # Content before opening tag
  989. after_tag = content[
  990. match.end() :
  991. ] # Content after opening tag
  992. # Remove the start tag and after from the currently handling text block
  993. content_blocks[-1]["content"] = content_blocks[-1][
  994. "content"
  995. ].replace(match.group(0) + after_tag, "")
  996. if before_tag:
  997. content_blocks[-1]["content"] = before_tag
  998. if not content_blocks[-1]["content"]:
  999. content_blocks.pop()
  1000. # Append the new block
  1001. content_blocks.append(
  1002. {
  1003. "type": content_type,
  1004. "tag": tag,
  1005. "attributes": attributes,
  1006. "content": "",
  1007. "started_at": time.time(),
  1008. }
  1009. )
  1010. if after_tag:
  1011. content_blocks[-1]["content"] = after_tag
  1012. break
  1013. elif content_blocks[-1]["type"] == content_type:
  1014. tag = content_blocks[-1]["tag"]
  1015. # Match end tag e.g., </tag>
  1016. end_tag_pattern = rf"</{tag}>"
  1017. # Check if the content has the end tag
  1018. if re.search(end_tag_pattern, content):
  1019. end_flag = True
  1020. block_content = content_blocks[-1]["content"]
  1021. # Strip start and end tags from the content
  1022. start_tag_pattern = rf"<{tag}(.*?)>"
  1023. block_content = re.sub(
  1024. start_tag_pattern, "", block_content
  1025. ).strip()
  1026. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1027. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1028. # Content inside the tag
  1029. block_content = (
  1030. split_content[0].strip() if split_content else ""
  1031. )
  1032. # Leftover content (everything after `</tag>`)
  1033. leftover_content = (
  1034. split_content[1].strip() if len(split_content) > 1 else ""
  1035. )
  1036. if block_content:
  1037. content_blocks[-1]["content"] = block_content
  1038. content_blocks[-1]["ended_at"] = time.time()
  1039. content_blocks[-1]["duration"] = int(
  1040. content_blocks[-1]["ended_at"]
  1041. - content_blocks[-1]["started_at"]
  1042. )
  1043. # Reset the content_blocks by appending a new text block
  1044. if content_type != "code_interpreter":
  1045. if leftover_content:
  1046. content_blocks.append(
  1047. {
  1048. "type": "text",
  1049. "content": leftover_content,
  1050. }
  1051. )
  1052. else:
  1053. content_blocks.append(
  1054. {
  1055. "type": "text",
  1056. "content": "",
  1057. }
  1058. )
  1059. else:
  1060. # Remove the block if content is empty
  1061. content_blocks.pop()
  1062. if leftover_content:
  1063. content_blocks.append(
  1064. {
  1065. "type": "text",
  1066. "content": leftover_content,
  1067. }
  1068. )
  1069. else:
  1070. content_blocks.append(
  1071. {
  1072. "type": "text",
  1073. "content": "",
  1074. }
  1075. )
  1076. # Clean processed content
  1077. content = re.sub(
  1078. rf"<{tag}(.*?)>(.|\n)*?</{tag}>",
  1079. "",
  1080. content,
  1081. flags=re.DOTALL,
  1082. )
  1083. return content, content_blocks, end_flag
  1084. message = Chats.get_message_by_id_and_message_id(
  1085. metadata["chat_id"], metadata["message_id"]
  1086. )
  1087. tool_calls = []
  1088. content = message.get("content", "") if message else ""
  1089. content_blocks = [
  1090. {
  1091. "type": "text",
  1092. "content": content,
  1093. }
  1094. ]
  1095. # We might want to disable this by default
  1096. DETECT_REASONING = True
  1097. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1098. "code_interpreter", False
  1099. )
  1100. reasoning_tags = [
  1101. "think",
  1102. "thinking",
  1103. "reason",
  1104. "reasoning",
  1105. "thought",
  1106. "Thought",
  1107. ]
  1108. code_interpreter_tags = ["code_interpreter"]
  1109. try:
  1110. for event in events:
  1111. await event_emitter(
  1112. {
  1113. "type": "chat:completion",
  1114. "data": event,
  1115. }
  1116. )
  1117. # Save message in the database
  1118. Chats.upsert_message_to_chat_by_id_and_message_id(
  1119. metadata["chat_id"],
  1120. metadata["message_id"],
  1121. {
  1122. **event,
  1123. },
  1124. )
  1125. async def stream_body_handler(response):
  1126. nonlocal content
  1127. nonlocal content_blocks
  1128. response_tool_calls = []
  1129. async for line in response.body_iterator:
  1130. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1131. data = line
  1132. # Skip empty lines
  1133. if not data.strip():
  1134. continue
  1135. # "data:" is the prefix for each event
  1136. if not data.startswith("data:"):
  1137. continue
  1138. # Remove the prefix
  1139. data = data[len("data:") :].strip()
  1140. try:
  1141. data = json.loads(data)
  1142. if "selected_model_id" in data:
  1143. model_id = data["selected_model_id"]
  1144. Chats.upsert_message_to_chat_by_id_and_message_id(
  1145. metadata["chat_id"],
  1146. metadata["message_id"],
  1147. {
  1148. "selectedModelId": model_id,
  1149. },
  1150. )
  1151. else:
  1152. choices = data.get("choices", [])
  1153. if not choices:
  1154. continue
  1155. delta = choices[0].get("delta", {})
  1156. delta_tool_calls = delta.get("tool_calls", None)
  1157. if delta_tool_calls:
  1158. for delta_tool_call in delta_tool_calls:
  1159. tool_call_index = delta_tool_call.get("index")
  1160. if tool_call_index is not None:
  1161. if (
  1162. len(response_tool_calls)
  1163. <= tool_call_index
  1164. ):
  1165. response_tool_calls.append(
  1166. delta_tool_call
  1167. )
  1168. else:
  1169. delta_name = delta_tool_call.get(
  1170. "function", {}
  1171. ).get("name")
  1172. delta_arguments = delta_tool_call.get(
  1173. "function", {}
  1174. ).get("arguments")
  1175. if delta_name:
  1176. response_tool_calls[
  1177. tool_call_index
  1178. ]["function"]["name"] += delta_name
  1179. if delta_arguments:
  1180. response_tool_calls[
  1181. tool_call_index
  1182. ]["function"][
  1183. "arguments"
  1184. ] += delta_arguments
  1185. value = delta.get("content")
  1186. if value:
  1187. content = f"{content}{value}"
  1188. if not content_blocks:
  1189. content_blocks.append(
  1190. {
  1191. "type": "text",
  1192. "content": "",
  1193. }
  1194. )
  1195. content_blocks[-1]["content"] = (
  1196. content_blocks[-1]["content"] + value
  1197. )
  1198. if DETECT_REASONING:
  1199. content, content_blocks, _ = (
  1200. tag_content_handler(
  1201. "reasoning",
  1202. reasoning_tags,
  1203. content,
  1204. content_blocks,
  1205. )
  1206. )
  1207. if DETECT_CODE_INTERPRETER:
  1208. content, content_blocks, end = (
  1209. tag_content_handler(
  1210. "code_interpreter",
  1211. code_interpreter_tags,
  1212. content,
  1213. content_blocks,
  1214. )
  1215. )
  1216. if end:
  1217. break
  1218. if ENABLE_REALTIME_CHAT_SAVE:
  1219. # Save message in the database
  1220. Chats.upsert_message_to_chat_by_id_and_message_id(
  1221. metadata["chat_id"],
  1222. metadata["message_id"],
  1223. {
  1224. "content": serialize_content_blocks(
  1225. content_blocks
  1226. ),
  1227. },
  1228. )
  1229. else:
  1230. data = {
  1231. "content": serialize_content_blocks(
  1232. content_blocks
  1233. ),
  1234. }
  1235. await event_emitter(
  1236. {
  1237. "type": "chat:completion",
  1238. "data": data,
  1239. }
  1240. )
  1241. except Exception as e:
  1242. done = "data: [DONE]" in line
  1243. if done:
  1244. pass
  1245. else:
  1246. log.debug("Error: ", e)
  1247. continue
  1248. if content_blocks:
  1249. # Clean up the last text block
  1250. if content_blocks[-1]["type"] == "text":
  1251. content_blocks[-1]["content"] = content_blocks[-1][
  1252. "content"
  1253. ].strip()
  1254. if not content_blocks[-1]["content"]:
  1255. content_blocks.pop()
  1256. if not content_blocks:
  1257. content_blocks.append(
  1258. {
  1259. "type": "text",
  1260. "content": "",
  1261. }
  1262. )
  1263. if response_tool_calls:
  1264. tool_calls.append(response_tool_calls)
  1265. if response.background:
  1266. await response.background()
  1267. await stream_body_handler(response)
  1268. MAX_TOOL_CALL_RETRIES = 5
  1269. tool_call_retries = 0
  1270. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1271. tool_call_retries += 1
  1272. response_tool_calls = tool_calls.pop(0)
  1273. content_blocks.append(
  1274. {
  1275. "type": "tool_calls",
  1276. "content": response_tool_calls,
  1277. }
  1278. )
  1279. await event_emitter(
  1280. {
  1281. "type": "chat:completion",
  1282. "data": {
  1283. "content": serialize_content_blocks(content_blocks),
  1284. },
  1285. }
  1286. )
  1287. tools = metadata.get("tools", {})
  1288. results = []
  1289. for tool_call in response_tool_calls:
  1290. print("\n\n" + str(tool_call) + "\n\n")
  1291. tool_call_id = tool_call.get("id", "")
  1292. tool_name = tool_call.get("function", {}).get("name", "")
  1293. tool_function_params = {}
  1294. try:
  1295. # json.loads cannot be used because some models do not produce valid JSON
  1296. tool_function_params = ast.literal_eval(
  1297. tool_call.get("function", {}).get("arguments", "{}")
  1298. )
  1299. except Exception as e:
  1300. log.debug(e)
  1301. tool_result = None
  1302. if tool_name in tools:
  1303. tool = tools[tool_name]
  1304. spec = tool.get("spec", {})
  1305. try:
  1306. required_params = spec.get("parameters", {}).get(
  1307. "required", []
  1308. )
  1309. tool_function = tool["callable"]
  1310. tool_function_params = {
  1311. k: v
  1312. for k, v in tool_function_params.items()
  1313. if k in required_params
  1314. }
  1315. tool_result = await tool_function(
  1316. **tool_function_params
  1317. )
  1318. except Exception as e:
  1319. tool_result = str(e)
  1320. results.append(
  1321. {
  1322. "tool_call_id": tool_call_id,
  1323. "content": tool_result,
  1324. }
  1325. )
  1326. content_blocks[-1]["results"] = results
  1327. content_blocks.append(
  1328. {
  1329. "type": "text",
  1330. "content": "",
  1331. }
  1332. )
  1333. await event_emitter(
  1334. {
  1335. "type": "chat:completion",
  1336. "data": {
  1337. "content": serialize_content_blocks(content_blocks),
  1338. },
  1339. }
  1340. )
  1341. try:
  1342. res = await generate_chat_completion(
  1343. request,
  1344. {
  1345. "model": model_id,
  1346. "stream": True,
  1347. "messages": [
  1348. *form_data["messages"],
  1349. {
  1350. "role": "assistant",
  1351. "content": serialize_content_blocks(
  1352. content_blocks, raw=True
  1353. ),
  1354. "tool_calls": response_tool_calls,
  1355. },
  1356. *[
  1357. {
  1358. "role": "tool",
  1359. "tool_call_id": result["tool_call_id"],
  1360. "content": result["content"],
  1361. }
  1362. for result in results
  1363. ],
  1364. ],
  1365. },
  1366. user,
  1367. )
  1368. if isinstance(res, StreamingResponse):
  1369. await stream_body_handler(res)
  1370. else:
  1371. break
  1372. except Exception as e:
  1373. log.debug(e)
  1374. break
  1375. if DETECT_CODE_INTERPRETER:
  1376. MAX_RETRIES = 5
  1377. retries = 0
  1378. while (
  1379. content_blocks[-1]["type"] == "code_interpreter"
  1380. and retries < MAX_RETRIES
  1381. ):
  1382. await event_emitter(
  1383. {
  1384. "type": "chat:completion",
  1385. "data": {
  1386. "content": serialize_content_blocks(content_blocks),
  1387. },
  1388. }
  1389. )
  1390. retries += 1
  1391. log.debug(f"Attempt count: {retries}")
  1392. output = ""
  1393. try:
  1394. if content_blocks[-1]["attributes"].get("type") == "code":
  1395. code = content_blocks[-1]["content"]
  1396. if (
  1397. request.app.state.config.CODE_INTERPRETER_ENGINE
  1398. == "pyodide"
  1399. ):
  1400. output = await event_caller(
  1401. {
  1402. "type": "execute:python",
  1403. "data": {
  1404. "id": str(uuid4()),
  1405. "code": code,
  1406. },
  1407. }
  1408. )
  1409. elif (
  1410. request.app.state.config.CODE_INTERPRETER_ENGINE
  1411. == "jupyter"
  1412. ):
  1413. output = await execute_code_jupyter(
  1414. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  1415. code,
  1416. (
  1417. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  1418. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1419. == "token"
  1420. else None
  1421. ),
  1422. (
  1423. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  1424. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1425. == "password"
  1426. else None
  1427. ),
  1428. )
  1429. else:
  1430. output = {
  1431. "stdout": "Code interpreter engine not configured."
  1432. }
  1433. if isinstance(output, dict):
  1434. stdout = output.get("stdout", "")
  1435. if stdout:
  1436. stdoutLines = stdout.split("\n")
  1437. for idx, line in enumerate(stdoutLines):
  1438. if "data:image/png;base64" in line:
  1439. id = str(uuid4())
  1440. # ensure the path exists
  1441. os.makedirs(
  1442. os.path.join(CACHE_DIR, "images"),
  1443. exist_ok=True,
  1444. )
  1445. image_path = os.path.join(
  1446. CACHE_DIR,
  1447. f"images/{id}.png",
  1448. )
  1449. with open(image_path, "wb") as f:
  1450. f.write(
  1451. base64.b64decode(
  1452. line.split(",")[1]
  1453. )
  1454. )
  1455. stdoutLines[idx] = (
  1456. f"![Output Image {idx}](/cache/images/{id}.png)"
  1457. )
  1458. output["stdout"] = "\n".join(stdoutLines)
  1459. result = output.get("result", "")
  1460. if result:
  1461. resultLines = result.split("\n")
  1462. for idx, line in enumerate(resultLines):
  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. resultLines[idx] = (
  1481. f"![Output Image {idx}](/cache/images/{id}.png)"
  1482. )
  1483. output["result"] = "\n".join(resultLines)
  1484. except Exception as e:
  1485. output = str(e)
  1486. content_blocks[-1]["output"] = output
  1487. content_blocks.append(
  1488. {
  1489. "type": "text",
  1490. "content": "",
  1491. }
  1492. )
  1493. await event_emitter(
  1494. {
  1495. "type": "chat:completion",
  1496. "data": {
  1497. "content": serialize_content_blocks(content_blocks),
  1498. },
  1499. }
  1500. )
  1501. try:
  1502. res = await generate_chat_completion(
  1503. request,
  1504. {
  1505. "model": model_id,
  1506. "stream": True,
  1507. "messages": [
  1508. *form_data["messages"],
  1509. {
  1510. "role": "assistant",
  1511. "content": serialize_content_blocks(
  1512. content_blocks, raw=True
  1513. ),
  1514. },
  1515. ],
  1516. },
  1517. user,
  1518. )
  1519. if isinstance(res, StreamingResponse):
  1520. await stream_body_handler(res)
  1521. else:
  1522. break
  1523. except Exception as e:
  1524. log.debug(e)
  1525. break
  1526. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1527. data = {
  1528. "done": True,
  1529. "content": serialize_content_blocks(content_blocks),
  1530. "title": title,
  1531. }
  1532. if not ENABLE_REALTIME_CHAT_SAVE:
  1533. # Save message in the database
  1534. Chats.upsert_message_to_chat_by_id_and_message_id(
  1535. metadata["chat_id"],
  1536. metadata["message_id"],
  1537. {
  1538. "content": serialize_content_blocks(content_blocks),
  1539. },
  1540. )
  1541. # Send a webhook notification if the user is not active
  1542. if get_active_status_by_user_id(user.id) is None:
  1543. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1544. if webhook_url:
  1545. post_webhook(
  1546. webhook_url,
  1547. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1548. {
  1549. "action": "chat",
  1550. "message": content,
  1551. "title": title,
  1552. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1553. },
  1554. )
  1555. await event_emitter(
  1556. {
  1557. "type": "chat:completion",
  1558. "data": data,
  1559. }
  1560. )
  1561. await background_tasks_handler()
  1562. except asyncio.CancelledError:
  1563. print("Task was cancelled!")
  1564. await event_emitter({"type": "task-cancelled"})
  1565. if not ENABLE_REALTIME_CHAT_SAVE:
  1566. # Save message in the database
  1567. Chats.upsert_message_to_chat_by_id_and_message_id(
  1568. metadata["chat_id"],
  1569. metadata["message_id"],
  1570. {
  1571. "content": serialize_content_blocks(content_blocks),
  1572. },
  1573. )
  1574. if response.background is not None:
  1575. await response.background()
  1576. # background_tasks.add_task(post_response_handler, response, events)
  1577. task_id, _ = create_task(post_response_handler(response, events))
  1578. return {"status": True, "task_id": task_id}
  1579. else:
  1580. # Fallback to the original response
  1581. async def stream_wrapper(original_generator, events):
  1582. def wrap_item(item):
  1583. return f"data: {item}\n\n"
  1584. for event in events:
  1585. yield wrap_item(json.dumps(event))
  1586. async for data in original_generator:
  1587. yield data
  1588. return StreamingResponse(
  1589. stream_wrapper(response.body_iterator, events),
  1590. headers=dict(response.headers),
  1591. background=response.background,
  1592. )