middleware.py 73 KB

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