middleware.py 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645
  1. import time
  2. import logging
  3. import sys
  4. import os
  5. import base64
  6. import textwrap
  7. import asyncio
  8. from aiocache import cached
  9. from typing import Any, Optional
  10. import random
  11. import json
  12. import html
  13. import inspect
  14. import re
  15. import ast
  16. from uuid import uuid4
  17. from concurrent.futures import ThreadPoolExecutor
  18. from fastapi import Request, HTTPException
  19. from starlette.responses import Response, StreamingResponse, JSONResponse
  20. from open_webui.models.chats import Chats
  21. from open_webui.models.folders import Folders
  22. from open_webui.models.users import Users
  23. from open_webui.socket.main import (
  24. get_event_call,
  25. get_event_emitter,
  26. get_active_status_by_user_id,
  27. )
  28. from open_webui.routers.tasks import (
  29. generate_queries,
  30. generate_title,
  31. generate_follow_ups,
  32. generate_image_prompt,
  33. generate_chat_tags,
  34. )
  35. from open_webui.routers.retrieval import process_web_search, SearchForm
  36. from open_webui.routers.images import (
  37. load_b64_image_data,
  38. image_generations,
  39. GenerateImageForm,
  40. upload_image,
  41. )
  42. from open_webui.routers.pipelines import (
  43. process_pipeline_inlet_filter,
  44. process_pipeline_outlet_filter,
  45. )
  46. from open_webui.routers.memories import query_memory, QueryMemoryForm
  47. from open_webui.utils.webhook import post_webhook
  48. from open_webui.models.users import UserModel
  49. from open_webui.models.functions import Functions
  50. from open_webui.models.models import Models
  51. from open_webui.retrieval.utils import get_sources_from_items
  52. from open_webui.utils.chat import generate_chat_completion
  53. from open_webui.utils.task import (
  54. get_task_model_id,
  55. rag_template,
  56. tools_function_calling_generation_template,
  57. )
  58. from open_webui.utils.misc import (
  59. deep_update,
  60. get_message_list,
  61. add_or_update_system_message,
  62. add_or_update_user_message,
  63. get_last_user_message,
  64. get_last_assistant_message,
  65. get_system_message,
  66. prepend_to_first_user_message_content,
  67. convert_logit_bias_input_to_json,
  68. )
  69. from open_webui.utils.tools import get_tools
  70. from open_webui.utils.plugin import load_function_module_by_id
  71. from open_webui.utils.filter import (
  72. get_sorted_filter_ids,
  73. process_filter_functions,
  74. )
  75. from open_webui.utils.code_interpreter import execute_code_jupyter
  76. from open_webui.utils.payload import apply_system_prompt_to_body
  77. from open_webui.config import (
  78. CACHE_DIR,
  79. DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  80. DEFAULT_CODE_INTERPRETER_PROMPT,
  81. CODE_INTERPRETER_BLOCKED_MODULES,
  82. )
  83. from open_webui.env import (
  84. SRC_LOG_LEVELS,
  85. GLOBAL_LOG_LEVEL,
  86. CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
  87. BYPASS_MODEL_ACCESS_CONTROL,
  88. ENABLE_REALTIME_CHAT_SAVE,
  89. )
  90. from open_webui.constants import TASKS
  91. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  92. log = logging.getLogger(__name__)
  93. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  94. async def chat_completion_tools_handler(
  95. request: Request, body: dict, extra_params: dict, user: UserModel, models, tools
  96. ) -> tuple[dict, dict]:
  97. async def get_content_from_response(response) -> Optional[str]:
  98. content = None
  99. if hasattr(response, "body_iterator"):
  100. async for chunk in response.body_iterator:
  101. data = json.loads(chunk.decode("utf-8"))
  102. content = data["choices"][0]["message"]["content"]
  103. # Cleanup any remaining background tasks if necessary
  104. if response.background is not None:
  105. await response.background()
  106. else:
  107. content = response["choices"][0]["message"]["content"]
  108. return content
  109. def get_tools_function_calling_payload(messages, task_model_id, content):
  110. user_message = get_last_user_message(messages)
  111. history = "\n".join(
  112. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  113. for message in messages[::-1][:4]
  114. )
  115. prompt = f"History:\n{history}\nQuery: {user_message}"
  116. return {
  117. "model": task_model_id,
  118. "messages": [
  119. {"role": "system", "content": content},
  120. {"role": "user", "content": f"Query: {prompt}"},
  121. ],
  122. "stream": False,
  123. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  124. }
  125. event_caller = extra_params["__event_call__"]
  126. metadata = extra_params["__metadata__"]
  127. task_model_id = get_task_model_id(
  128. body["model"],
  129. request.app.state.config.TASK_MODEL,
  130. request.app.state.config.TASK_MODEL_EXTERNAL,
  131. models,
  132. )
  133. skip_files = False
  134. sources = []
  135. specs = [tool["spec"] for tool in tools.values()]
  136. tools_specs = json.dumps(specs)
  137. if request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  138. template = request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  139. else:
  140. template = DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  141. tools_function_calling_prompt = tools_function_calling_generation_template(
  142. template, tools_specs
  143. )
  144. payload = get_tools_function_calling_payload(
  145. body["messages"], task_model_id, tools_function_calling_prompt
  146. )
  147. try:
  148. response = await generate_chat_completion(request, form_data=payload, user=user)
  149. log.debug(f"{response=}")
  150. content = await get_content_from_response(response)
  151. log.debug(f"{content=}")
  152. if not content:
  153. return body, {}
  154. try:
  155. content = content[content.find("{") : content.rfind("}") + 1]
  156. if not content:
  157. raise Exception("No JSON object found in the response")
  158. result = json.loads(content)
  159. async def tool_call_handler(tool_call):
  160. nonlocal skip_files
  161. log.debug(f"{tool_call=}")
  162. tool_function_name = tool_call.get("name", None)
  163. if tool_function_name not in tools:
  164. return body, {}
  165. tool_function_params = tool_call.get("parameters", {})
  166. try:
  167. tool = tools[tool_function_name]
  168. spec = tool.get("spec", {})
  169. allowed_params = (
  170. spec.get("parameters", {}).get("properties", {}).keys()
  171. )
  172. tool_function_params = {
  173. k: v
  174. for k, v in tool_function_params.items()
  175. if k in allowed_params
  176. }
  177. if tool.get("direct", False):
  178. tool_result = await event_caller(
  179. {
  180. "type": "execute:tool",
  181. "data": {
  182. "id": str(uuid4()),
  183. "name": tool_function_name,
  184. "params": tool_function_params,
  185. "server": tool.get("server", {}),
  186. "session_id": metadata.get("session_id", None),
  187. },
  188. }
  189. )
  190. else:
  191. tool_function = tool["callable"]
  192. tool_result = await tool_function(**tool_function_params)
  193. except Exception as e:
  194. tool_result = str(e)
  195. tool_result_files = []
  196. if isinstance(tool_result, list):
  197. for item in tool_result:
  198. # check if string
  199. if isinstance(item, str) and item.startswith("data:"):
  200. tool_result_files.append(item)
  201. tool_result.remove(item)
  202. if isinstance(tool_result, dict) or isinstance(tool_result, list):
  203. tool_result = json.dumps(tool_result, indent=2)
  204. if isinstance(tool_result, str):
  205. tool = tools[tool_function_name]
  206. tool_id = tool.get("tool_id", "")
  207. tool_name = (
  208. f"{tool_id}/{tool_function_name}"
  209. if tool_id
  210. else f"{tool_function_name}"
  211. )
  212. # Citation is enabled for this tool
  213. sources.append(
  214. {
  215. "source": {
  216. "name": (f"TOOL:{tool_name}"),
  217. },
  218. "document": [tool_result],
  219. "metadata": [
  220. {
  221. "source": (f"TOOL:{tool_name}"),
  222. "parameters": tool_function_params,
  223. }
  224. ],
  225. "tool_result": True,
  226. }
  227. )
  228. # Citation is not enabled for this tool
  229. body["messages"] = add_or_update_user_message(
  230. f"\nTool `{tool_name}` Output: {tool_result}",
  231. body["messages"],
  232. )
  233. if (
  234. tools[tool_function_name]
  235. .get("metadata", {})
  236. .get("file_handler", False)
  237. ):
  238. skip_files = True
  239. # check if "tool_calls" in result
  240. if result.get("tool_calls"):
  241. for tool_call in result.get("tool_calls"):
  242. await tool_call_handler(tool_call)
  243. else:
  244. await tool_call_handler(result)
  245. except Exception as e:
  246. log.debug(f"Error: {e}")
  247. content = None
  248. except Exception as e:
  249. log.debug(f"Error: {e}")
  250. content = None
  251. log.debug(f"tool_contexts: {sources}")
  252. if skip_files and "files" in body.get("metadata", {}):
  253. del body["metadata"]["files"]
  254. return body, {"sources": sources}
  255. async def chat_memory_handler(
  256. request: Request, form_data: dict, extra_params: dict, user
  257. ):
  258. try:
  259. results = await query_memory(
  260. request,
  261. QueryMemoryForm(
  262. **{
  263. "content": get_last_user_message(form_data["messages"]) or "",
  264. "k": 3,
  265. }
  266. ),
  267. user,
  268. )
  269. except Exception as e:
  270. log.debug(e)
  271. results = None
  272. user_context = ""
  273. if results and hasattr(results, "documents"):
  274. if results.documents and len(results.documents) > 0:
  275. for doc_idx, doc in enumerate(results.documents[0]):
  276. created_at_date = "Unknown Date"
  277. if results.metadatas[0][doc_idx].get("created_at"):
  278. created_at_timestamp = results.metadatas[0][doc_idx]["created_at"]
  279. created_at_date = time.strftime(
  280. "%Y-%m-%d", time.localtime(created_at_timestamp)
  281. )
  282. user_context += f"{doc_idx + 1}. [{created_at_date}] {doc}\n"
  283. form_data["messages"] = add_or_update_system_message(
  284. f"User Context:\n{user_context}\n", form_data["messages"], append=True
  285. )
  286. return form_data
  287. async def chat_web_search_handler(
  288. request: Request, form_data: dict, extra_params: dict, user
  289. ):
  290. event_emitter = extra_params["__event_emitter__"]
  291. await event_emitter(
  292. {
  293. "type": "status",
  294. "data": {
  295. "action": "web_search",
  296. "description": "Generating search query",
  297. "done": False,
  298. },
  299. }
  300. )
  301. messages = form_data["messages"]
  302. user_message = get_last_user_message(messages)
  303. queries = []
  304. try:
  305. res = await generate_queries(
  306. request,
  307. {
  308. "model": form_data["model"],
  309. "messages": messages,
  310. "prompt": user_message,
  311. "type": "web_search",
  312. },
  313. user,
  314. )
  315. response = res["choices"][0]["message"]["content"]
  316. try:
  317. bracket_start = response.find("{")
  318. bracket_end = response.rfind("}") + 1
  319. if bracket_start == -1 or bracket_end == -1:
  320. raise Exception("No JSON object found in the response")
  321. response = response[bracket_start:bracket_end]
  322. queries = json.loads(response)
  323. queries = queries.get("queries", [])
  324. except Exception as e:
  325. queries = [response]
  326. except Exception as e:
  327. log.exception(e)
  328. queries = [user_message]
  329. # Check if generated queries are empty
  330. if len(queries) == 1 and queries[0].strip() == "":
  331. queries = [user_message]
  332. # Check if queries are not found
  333. if len(queries) == 0:
  334. await event_emitter(
  335. {
  336. "type": "status",
  337. "data": {
  338. "action": "web_search",
  339. "description": "No search query generated",
  340. "done": True,
  341. },
  342. }
  343. )
  344. return form_data
  345. await event_emitter(
  346. {
  347. "type": "status",
  348. "data": {
  349. "action": "web_search",
  350. "description": "Searching the web",
  351. "done": False,
  352. },
  353. }
  354. )
  355. try:
  356. results = await process_web_search(
  357. request,
  358. SearchForm(queries=queries),
  359. user=user,
  360. )
  361. if results:
  362. files = form_data.get("files", [])
  363. if results.get("collection_names"):
  364. for col_idx, collection_name in enumerate(
  365. results.get("collection_names")
  366. ):
  367. files.append(
  368. {
  369. "collection_name": collection_name,
  370. "name": ", ".join(queries),
  371. "type": "web_search",
  372. "urls": results["filenames"],
  373. "queries": queries,
  374. }
  375. )
  376. elif results.get("docs"):
  377. # Invoked when bypass embedding and retrieval is set to True
  378. docs = results["docs"]
  379. files.append(
  380. {
  381. "docs": docs,
  382. "name": ", ".join(queries),
  383. "type": "web_search",
  384. "urls": results["filenames"],
  385. "queries": queries,
  386. }
  387. )
  388. form_data["files"] = files
  389. await event_emitter(
  390. {
  391. "type": "status",
  392. "data": {
  393. "action": "web_search",
  394. "description": "Searched {{count}} sites",
  395. "urls": results["filenames"],
  396. "done": True,
  397. },
  398. }
  399. )
  400. else:
  401. await event_emitter(
  402. {
  403. "type": "status",
  404. "data": {
  405. "action": "web_search",
  406. "description": "No search results found",
  407. "done": True,
  408. "error": True,
  409. },
  410. }
  411. )
  412. except Exception as e:
  413. log.exception(e)
  414. await event_emitter(
  415. {
  416. "type": "status",
  417. "data": {
  418. "action": "web_search",
  419. "description": "An error occurred while searching the web",
  420. "queries": queries,
  421. "done": True,
  422. "error": True,
  423. },
  424. }
  425. )
  426. return form_data
  427. async def chat_image_generation_handler(
  428. request: Request, form_data: dict, extra_params: dict, user
  429. ):
  430. __event_emitter__ = extra_params["__event_emitter__"]
  431. await __event_emitter__(
  432. {
  433. "type": "status",
  434. "data": {"description": "Generating an image", "done": False},
  435. }
  436. )
  437. messages = form_data["messages"]
  438. user_message = get_last_user_message(messages)
  439. prompt = user_message
  440. negative_prompt = ""
  441. if request.app.state.config.ENABLE_IMAGE_PROMPT_GENERATION:
  442. try:
  443. res = await generate_image_prompt(
  444. request,
  445. {
  446. "model": form_data["model"],
  447. "messages": messages,
  448. },
  449. user,
  450. )
  451. response = res["choices"][0]["message"]["content"]
  452. try:
  453. bracket_start = response.find("{")
  454. bracket_end = response.rfind("}") + 1
  455. if bracket_start == -1 or bracket_end == -1:
  456. raise Exception("No JSON object found in the response")
  457. response = response[bracket_start:bracket_end]
  458. response = json.loads(response)
  459. prompt = response.get("prompt", [])
  460. except Exception as e:
  461. prompt = user_message
  462. except Exception as e:
  463. log.exception(e)
  464. prompt = user_message
  465. system_message_content = ""
  466. try:
  467. images = await image_generations(
  468. request=request,
  469. form_data=GenerateImageForm(**{"prompt": prompt}),
  470. user=user,
  471. )
  472. await __event_emitter__(
  473. {
  474. "type": "status",
  475. "data": {"description": "Generated an image", "done": True},
  476. }
  477. )
  478. await __event_emitter__(
  479. {
  480. "type": "files",
  481. "data": {
  482. "files": [
  483. {
  484. "type": "image",
  485. "url": image["url"],
  486. }
  487. for image in images
  488. ]
  489. },
  490. }
  491. )
  492. system_message_content = "<context>User is shown the generated image, tell the user that the image has been generated</context>"
  493. except Exception as e:
  494. log.exception(e)
  495. await __event_emitter__(
  496. {
  497. "type": "status",
  498. "data": {
  499. "description": f"An error occurred while generating an image",
  500. "done": True,
  501. },
  502. }
  503. )
  504. system_message_content = "<context>Unable to generate an image, tell the user that an error occurred</context>"
  505. if system_message_content:
  506. form_data["messages"] = add_or_update_system_message(
  507. system_message_content, form_data["messages"]
  508. )
  509. return form_data
  510. async def chat_completion_files_handler(
  511. request: Request, body: dict, user: UserModel
  512. ) -> tuple[dict, dict[str, list]]:
  513. sources = []
  514. if files := body.get("metadata", {}).get("files", None):
  515. queries = []
  516. try:
  517. queries_response = await generate_queries(
  518. request,
  519. {
  520. "model": body["model"],
  521. "messages": body["messages"],
  522. "type": "retrieval",
  523. },
  524. user,
  525. )
  526. queries_response = queries_response["choices"][0]["message"]["content"]
  527. try:
  528. bracket_start = queries_response.find("{")
  529. bracket_end = queries_response.rfind("}") + 1
  530. if bracket_start == -1 or bracket_end == -1:
  531. raise Exception("No JSON object found in the response")
  532. queries_response = queries_response[bracket_start:bracket_end]
  533. queries_response = json.loads(queries_response)
  534. except Exception as e:
  535. queries_response = {"queries": [queries_response]}
  536. queries = queries_response.get("queries", [])
  537. except:
  538. pass
  539. if len(queries) == 0:
  540. queries = [get_last_user_message(body["messages"])]
  541. try:
  542. # Offload get_sources_from_items to a separate thread
  543. loop = asyncio.get_running_loop()
  544. with ThreadPoolExecutor() as executor:
  545. sources = await loop.run_in_executor(
  546. executor,
  547. lambda: get_sources_from_items(
  548. request=request,
  549. items=files,
  550. queries=queries,
  551. embedding_function=lambda query, prefix: request.app.state.EMBEDDING_FUNCTION(
  552. query, prefix=prefix, user=user
  553. ),
  554. k=request.app.state.config.TOP_K,
  555. reranking_function=(
  556. (
  557. lambda sentences: request.app.state.RERANKING_FUNCTION(
  558. sentences, user=user
  559. )
  560. )
  561. if request.app.state.RERANKING_FUNCTION
  562. else None
  563. ),
  564. k_reranker=request.app.state.config.TOP_K_RERANKER,
  565. r=request.app.state.config.RELEVANCE_THRESHOLD,
  566. hybrid_bm25_weight=request.app.state.config.HYBRID_BM25_WEIGHT,
  567. hybrid_search=request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  568. full_context=request.app.state.config.RAG_FULL_CONTEXT,
  569. user=user,
  570. ),
  571. )
  572. except Exception as e:
  573. log.exception(e)
  574. log.debug(f"rag_contexts:sources: {sources}")
  575. return body, {"sources": sources}
  576. def apply_params_to_form_data(form_data, model):
  577. params = form_data.pop("params", {})
  578. custom_params = params.pop("custom_params", {})
  579. open_webui_params = {
  580. "stream_response": bool,
  581. "stream_delta_chunk_size": int,
  582. "function_calling": str,
  583. "system": str,
  584. }
  585. for key in list(params.keys()):
  586. if key in open_webui_params:
  587. del params[key]
  588. if custom_params:
  589. # Attempt to parse custom_params if they are strings
  590. for key, value in custom_params.items():
  591. if isinstance(value, str):
  592. try:
  593. # Attempt to parse the string as JSON
  594. custom_params[key] = json.loads(value)
  595. except json.JSONDecodeError:
  596. # If it fails, keep the original string
  597. pass
  598. # If custom_params are provided, merge them into params
  599. params = deep_update(params, custom_params)
  600. if model.get("owned_by") == "ollama":
  601. # Ollama specific parameters
  602. form_data["options"] = params
  603. else:
  604. if isinstance(params, dict):
  605. for key, value in params.items():
  606. if value is not None:
  607. form_data[key] = value
  608. if "logit_bias" in params and params["logit_bias"] is not None:
  609. try:
  610. form_data["logit_bias"] = json.loads(
  611. convert_logit_bias_input_to_json(params["logit_bias"])
  612. )
  613. except Exception as e:
  614. log.exception(f"Error parsing logit_bias: {e}")
  615. return form_data
  616. async def process_chat_payload(request, form_data, user, metadata, model):
  617. # Pipeline Inlet -> Filter Inlet -> Chat Memory -> Chat Web Search -> Chat Image Generation
  618. # -> Chat Code Interpreter (Form Data Update) -> (Default) Chat Tools Function Calling
  619. # -> Chat Files
  620. form_data = apply_params_to_form_data(form_data, model)
  621. log.debug(f"form_data: {form_data}")
  622. system_message = get_system_message(form_data.get("messages", []))
  623. if system_message:
  624. form_data = apply_system_prompt_to_body(
  625. system_message.get("content"), form_data, metadata, user
  626. )
  627. event_emitter = get_event_emitter(metadata)
  628. event_call = get_event_call(metadata)
  629. extra_params = {
  630. "__event_emitter__": event_emitter,
  631. "__event_call__": event_call,
  632. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  633. "__metadata__": metadata,
  634. "__request__": request,
  635. "__model__": model,
  636. }
  637. # Initialize events to store additional event to be sent to the client
  638. # Initialize contexts and citation
  639. if getattr(request.state, "direct", False) and hasattr(request.state, "model"):
  640. models = {
  641. request.state.model["id"]: request.state.model,
  642. }
  643. else:
  644. models = request.app.state.MODELS
  645. task_model_id = get_task_model_id(
  646. form_data["model"],
  647. request.app.state.config.TASK_MODEL,
  648. request.app.state.config.TASK_MODEL_EXTERNAL,
  649. models,
  650. )
  651. events = []
  652. sources = []
  653. # Folder "Project" handling
  654. # Check if the request has chat_id and is inside of a folder
  655. chat_id = metadata.get("chat_id", None)
  656. if chat_id and user:
  657. chat = Chats.get_chat_by_id_and_user_id(chat_id, user.id)
  658. if chat and chat.folder_id:
  659. folder = Folders.get_folder_by_id_and_user_id(chat.folder_id, user.id)
  660. if folder and folder.data:
  661. if "system_prompt" in folder.data:
  662. form_data = apply_system_prompt_to_body(
  663. folder.data["system_prompt"], form_data, metadata, user
  664. )
  665. if "files" in folder.data:
  666. form_data["files"] = [
  667. *folder.data["files"],
  668. *form_data.get("files", []),
  669. ]
  670. # Model "Knowledge" handling
  671. user_message = get_last_user_message(form_data["messages"])
  672. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  673. if model_knowledge:
  674. await event_emitter(
  675. {
  676. "type": "status",
  677. "data": {
  678. "action": "knowledge_search",
  679. "query": user_message,
  680. "done": False,
  681. },
  682. }
  683. )
  684. knowledge_files = []
  685. for item in model_knowledge:
  686. if item.get("collection_name"):
  687. knowledge_files.append(
  688. {
  689. "id": item.get("collection_name"),
  690. "name": item.get("name"),
  691. "legacy": True,
  692. }
  693. )
  694. elif item.get("collection_names"):
  695. knowledge_files.append(
  696. {
  697. "name": item.get("name"),
  698. "type": "collection",
  699. "collection_names": item.get("collection_names"),
  700. "legacy": True,
  701. }
  702. )
  703. else:
  704. knowledge_files.append(item)
  705. files = form_data.get("files", [])
  706. files.extend(knowledge_files)
  707. form_data["files"] = files
  708. variables = form_data.pop("variables", None)
  709. # Process the form_data through the pipeline
  710. try:
  711. form_data = await process_pipeline_inlet_filter(
  712. request, form_data, user, models
  713. )
  714. except Exception as e:
  715. raise e
  716. try:
  717. filter_functions = [
  718. Functions.get_function_by_id(filter_id)
  719. for filter_id in get_sorted_filter_ids(
  720. request, model, metadata.get("filter_ids", [])
  721. )
  722. ]
  723. form_data, flags = await process_filter_functions(
  724. request=request,
  725. filter_functions=filter_functions,
  726. filter_type="inlet",
  727. form_data=form_data,
  728. extra_params=extra_params,
  729. )
  730. except Exception as e:
  731. raise Exception(f"Error: {e}")
  732. features = form_data.pop("features", None)
  733. if features:
  734. if "memory" in features and features["memory"]:
  735. form_data = await chat_memory_handler(
  736. request, form_data, extra_params, user
  737. )
  738. if "web_search" in features and features["web_search"]:
  739. form_data = await chat_web_search_handler(
  740. request, form_data, extra_params, user
  741. )
  742. if "image_generation" in features and features["image_generation"]:
  743. form_data = await chat_image_generation_handler(
  744. request, form_data, extra_params, user
  745. )
  746. if "code_interpreter" in features and features["code_interpreter"]:
  747. form_data["messages"] = add_or_update_user_message(
  748. (
  749. request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE
  750. if request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE != ""
  751. else DEFAULT_CODE_INTERPRETER_PROMPT
  752. ),
  753. form_data["messages"],
  754. )
  755. tool_ids = form_data.pop("tool_ids", None)
  756. files = form_data.pop("files", None)
  757. # Remove files duplicates
  758. if files:
  759. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  760. metadata = {
  761. **metadata,
  762. "tool_ids": tool_ids,
  763. "files": files,
  764. }
  765. form_data["metadata"] = metadata
  766. # Server side tools
  767. tool_ids = metadata.get("tool_ids", None)
  768. # Client side tools
  769. tool_servers = metadata.get("tool_servers", None)
  770. log.debug(f"{tool_ids=}")
  771. log.debug(f"{tool_servers=}")
  772. tools_dict = {}
  773. if tool_ids:
  774. tools_dict = await get_tools(
  775. request,
  776. tool_ids,
  777. user,
  778. {
  779. **extra_params,
  780. "__model__": models[task_model_id],
  781. "__messages__": form_data["messages"],
  782. "__files__": metadata.get("files", []),
  783. },
  784. )
  785. if tool_servers:
  786. for tool_server in tool_servers:
  787. tool_specs = tool_server.pop("specs", [])
  788. for tool in tool_specs:
  789. tools_dict[tool["name"]] = {
  790. "spec": tool,
  791. "direct": True,
  792. "server": tool_server,
  793. }
  794. if tools_dict:
  795. if metadata.get("params", {}).get("function_calling") == "native":
  796. # If the function calling is native, then call the tools function calling handler
  797. metadata["tools"] = tools_dict
  798. form_data["tools"] = [
  799. {"type": "function", "function": tool.get("spec", {})}
  800. for tool in tools_dict.values()
  801. ]
  802. else:
  803. # If the function calling is not native, then call the tools function calling handler
  804. try:
  805. form_data, flags = await chat_completion_tools_handler(
  806. request, form_data, extra_params, user, models, tools_dict
  807. )
  808. sources.extend(flags.get("sources", []))
  809. except Exception as e:
  810. log.exception(e)
  811. try:
  812. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  813. sources.extend(flags.get("sources", []))
  814. except Exception as e:
  815. log.exception(e)
  816. # If context is not empty, insert it into the messages
  817. if len(sources) > 0:
  818. context_string = ""
  819. citation_idx_map = {}
  820. for source in sources:
  821. is_tool_result = source.get("tool_result", False)
  822. if "document" in source and not is_tool_result:
  823. for document_text, document_metadata in zip(
  824. source["document"], source["metadata"]
  825. ):
  826. source_name = source.get("source", {}).get("name", None)
  827. source_id = (
  828. document_metadata.get("source", None)
  829. or source.get("source", {}).get("id", None)
  830. or "N/A"
  831. )
  832. if source_id not in citation_idx_map:
  833. citation_idx_map[source_id] = len(citation_idx_map) + 1
  834. context_string += (
  835. f'<source id="{citation_idx_map[source_id]}"'
  836. + (f' name="{source_name}"' if source_name else "")
  837. + f">{document_text}</source>\n"
  838. )
  839. context_string = context_string.strip()
  840. prompt = get_last_user_message(form_data["messages"])
  841. if prompt is None:
  842. raise Exception("No user message found")
  843. if context_string != "":
  844. # Workaround for Ollama 2.0+ system prompt issue
  845. # TODO: replace with add_or_update_system_message
  846. if model.get("owned_by") == "ollama":
  847. form_data["messages"] = prepend_to_first_user_message_content(
  848. rag_template(
  849. request.app.state.config.RAG_TEMPLATE,
  850. context_string,
  851. prompt,
  852. ),
  853. form_data["messages"],
  854. )
  855. else:
  856. form_data["messages"] = add_or_update_system_message(
  857. rag_template(
  858. request.app.state.config.RAG_TEMPLATE,
  859. context_string,
  860. prompt,
  861. ),
  862. form_data["messages"],
  863. )
  864. # If there are citations, add them to the data_items
  865. sources = [
  866. source
  867. for source in sources
  868. if source.get("source", {}).get("name", "")
  869. or source.get("source", {}).get("id", "")
  870. ]
  871. if len(sources) > 0:
  872. events.append({"sources": sources})
  873. if model_knowledge:
  874. await event_emitter(
  875. {
  876. "type": "status",
  877. "data": {
  878. "action": "knowledge_search",
  879. "query": user_message,
  880. "done": True,
  881. "hidden": True,
  882. },
  883. }
  884. )
  885. return form_data, metadata, events
  886. async def process_chat_response(
  887. request, response, form_data, user, metadata, model, events, tasks
  888. ):
  889. async def background_tasks_handler():
  890. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  891. message = message_map.get(metadata["message_id"]) if message_map else None
  892. if message:
  893. message_list = get_message_list(message_map, metadata["message_id"])
  894. # Remove details tags and files from the messages.
  895. # as get_message_list creates a new list, it does not affect
  896. # the original messages outside of this handler
  897. messages = []
  898. for message in message_list:
  899. content = message.get("content", "")
  900. if isinstance(content, list):
  901. for item in content:
  902. if item.get("type") == "text":
  903. content = item["text"]
  904. break
  905. if isinstance(content, str):
  906. content = re.sub(
  907. r"<details\b[^>]*>.*?<\/details>|!\[.*?\]\(.*?\)",
  908. "",
  909. content,
  910. flags=re.S | re.I,
  911. ).strip()
  912. messages.append(
  913. {
  914. **message,
  915. "role": message.get(
  916. "role", "assistant"
  917. ), # Safe fallback for missing role
  918. "content": content,
  919. }
  920. )
  921. if tasks and messages:
  922. if (
  923. TASKS.FOLLOW_UP_GENERATION in tasks
  924. and tasks[TASKS.FOLLOW_UP_GENERATION]
  925. ):
  926. res = await generate_follow_ups(
  927. request,
  928. {
  929. "model": message["model"],
  930. "messages": messages,
  931. "message_id": metadata["message_id"],
  932. "chat_id": metadata["chat_id"],
  933. },
  934. user,
  935. )
  936. if res and isinstance(res, dict):
  937. if len(res.get("choices", [])) == 1:
  938. follow_ups_string = (
  939. res.get("choices", [])[0]
  940. .get("message", {})
  941. .get("content", "")
  942. )
  943. else:
  944. follow_ups_string = ""
  945. follow_ups_string = follow_ups_string[
  946. follow_ups_string.find("{") : follow_ups_string.rfind("}")
  947. + 1
  948. ]
  949. try:
  950. follow_ups = json.loads(follow_ups_string).get(
  951. "follow_ups", []
  952. )
  953. Chats.upsert_message_to_chat_by_id_and_message_id(
  954. metadata["chat_id"],
  955. metadata["message_id"],
  956. {
  957. "followUps": follow_ups,
  958. },
  959. )
  960. await event_emitter(
  961. {
  962. "type": "chat:message:follow_ups",
  963. "data": {
  964. "follow_ups": follow_ups,
  965. },
  966. }
  967. )
  968. except Exception as e:
  969. pass
  970. if TASKS.TITLE_GENERATION in tasks:
  971. user_message = get_last_user_message(messages)
  972. if user_message and len(user_message) > 100:
  973. user_message = user_message[:100] + "..."
  974. if tasks[TASKS.TITLE_GENERATION]:
  975. res = await generate_title(
  976. request,
  977. {
  978. "model": message["model"],
  979. "messages": messages,
  980. "chat_id": metadata["chat_id"],
  981. },
  982. user,
  983. )
  984. if res and isinstance(res, dict):
  985. if len(res.get("choices", [])) == 1:
  986. title_string = (
  987. res.get("choices", [])[0]
  988. .get("message", {})
  989. .get(
  990. "content", message.get("content", user_message)
  991. )
  992. )
  993. else:
  994. title_string = ""
  995. title_string = title_string[
  996. title_string.find("{") : title_string.rfind("}") + 1
  997. ]
  998. try:
  999. title = json.loads(title_string).get(
  1000. "title", user_message
  1001. )
  1002. except Exception as e:
  1003. title = ""
  1004. if not title:
  1005. title = messages[0].get("content", user_message)
  1006. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1007. await event_emitter(
  1008. {
  1009. "type": "chat:title",
  1010. "data": title,
  1011. }
  1012. )
  1013. elif len(messages) == 2:
  1014. title = messages[0].get("content", user_message)
  1015. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1016. await event_emitter(
  1017. {
  1018. "type": "chat:title",
  1019. "data": message.get("content", user_message),
  1020. }
  1021. )
  1022. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  1023. res = await generate_chat_tags(
  1024. request,
  1025. {
  1026. "model": message["model"],
  1027. "messages": messages,
  1028. "chat_id": metadata["chat_id"],
  1029. },
  1030. user,
  1031. )
  1032. if res and isinstance(res, dict):
  1033. if len(res.get("choices", [])) == 1:
  1034. tags_string = (
  1035. res.get("choices", [])[0]
  1036. .get("message", {})
  1037. .get("content", "")
  1038. )
  1039. else:
  1040. tags_string = ""
  1041. tags_string = tags_string[
  1042. tags_string.find("{") : tags_string.rfind("}") + 1
  1043. ]
  1044. try:
  1045. tags = json.loads(tags_string).get("tags", [])
  1046. Chats.update_chat_tags_by_id(
  1047. metadata["chat_id"], tags, user
  1048. )
  1049. await event_emitter(
  1050. {
  1051. "type": "chat:tags",
  1052. "data": tags,
  1053. }
  1054. )
  1055. except Exception as e:
  1056. pass
  1057. event_emitter = None
  1058. event_caller = None
  1059. if (
  1060. "session_id" in metadata
  1061. and metadata["session_id"]
  1062. and "chat_id" in metadata
  1063. and metadata["chat_id"]
  1064. and "message_id" in metadata
  1065. and metadata["message_id"]
  1066. ):
  1067. event_emitter = get_event_emitter(metadata)
  1068. event_caller = get_event_call(metadata)
  1069. # Non-streaming response
  1070. if not isinstance(response, StreamingResponse):
  1071. if event_emitter:
  1072. if isinstance(response, dict) or isinstance(response, JSONResponse):
  1073. if isinstance(response, JSONResponse) and isinstance(
  1074. response.body, bytes
  1075. ):
  1076. try:
  1077. response_data = json.loads(response.body.decode("utf-8"))
  1078. except json.JSONDecodeError:
  1079. response_data = {"error": {"detail": "Invalid JSON response"}}
  1080. else:
  1081. response_data = response
  1082. if "error" in response_data:
  1083. error = response_data["error"].get("detail", response_data["error"])
  1084. Chats.upsert_message_to_chat_by_id_and_message_id(
  1085. metadata["chat_id"],
  1086. metadata["message_id"],
  1087. {
  1088. "error": {"content": error},
  1089. },
  1090. )
  1091. if "selected_model_id" in response_data:
  1092. Chats.upsert_message_to_chat_by_id_and_message_id(
  1093. metadata["chat_id"],
  1094. metadata["message_id"],
  1095. {
  1096. "selectedModelId": response_data["selected_model_id"],
  1097. },
  1098. )
  1099. choices = response_data.get("choices", [])
  1100. if choices and choices[0].get("message", {}).get("content"):
  1101. content = response_data["choices"][0]["message"]["content"]
  1102. if content:
  1103. await event_emitter(
  1104. {
  1105. "type": "chat:completion",
  1106. "data": response_data,
  1107. }
  1108. )
  1109. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1110. await event_emitter(
  1111. {
  1112. "type": "chat:completion",
  1113. "data": {
  1114. "done": True,
  1115. "content": content,
  1116. "title": title,
  1117. },
  1118. }
  1119. )
  1120. # Save message in the database
  1121. Chats.upsert_message_to_chat_by_id_and_message_id(
  1122. metadata["chat_id"],
  1123. metadata["message_id"],
  1124. {
  1125. "role": "assistant",
  1126. "content": content,
  1127. },
  1128. )
  1129. # Send a webhook notification if the user is not active
  1130. if not get_active_status_by_user_id(user.id):
  1131. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1132. if webhook_url:
  1133. await post_webhook(
  1134. request.app.state.WEBUI_NAME,
  1135. webhook_url,
  1136. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1137. {
  1138. "action": "chat",
  1139. "message": content,
  1140. "title": title,
  1141. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1142. },
  1143. )
  1144. await background_tasks_handler()
  1145. if events and isinstance(events, list):
  1146. extra_response = {}
  1147. for event in events:
  1148. if isinstance(event, dict):
  1149. extra_response.update(event)
  1150. else:
  1151. extra_response[event] = True
  1152. response_data = {
  1153. **extra_response,
  1154. **response_data,
  1155. }
  1156. if isinstance(response, dict):
  1157. response = response_data
  1158. if isinstance(response, JSONResponse):
  1159. response = JSONResponse(
  1160. content=response_data,
  1161. headers=response.headers,
  1162. status_code=response.status_code,
  1163. )
  1164. return response
  1165. else:
  1166. if events and isinstance(events, list) and isinstance(response, dict):
  1167. extra_response = {}
  1168. for event in events:
  1169. if isinstance(event, dict):
  1170. extra_response.update(event)
  1171. else:
  1172. extra_response[event] = True
  1173. response = {
  1174. **extra_response,
  1175. **response,
  1176. }
  1177. return response
  1178. # Non standard response
  1179. if not any(
  1180. content_type in response.headers["Content-Type"]
  1181. for content_type in ["text/event-stream", "application/x-ndjson"]
  1182. ):
  1183. return response
  1184. extra_params = {
  1185. "__event_emitter__": event_emitter,
  1186. "__event_call__": event_caller,
  1187. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  1188. "__metadata__": metadata,
  1189. "__request__": request,
  1190. "__model__": model,
  1191. }
  1192. filter_functions = [
  1193. Functions.get_function_by_id(filter_id)
  1194. for filter_id in get_sorted_filter_ids(
  1195. request, model, metadata.get("filter_ids", [])
  1196. )
  1197. ]
  1198. # Streaming response
  1199. if event_emitter and event_caller:
  1200. task_id = str(uuid4()) # Create a unique task ID.
  1201. model_id = form_data.get("model", "")
  1202. def split_content_and_whitespace(content):
  1203. content_stripped = content.rstrip()
  1204. original_whitespace = (
  1205. content[len(content_stripped) :]
  1206. if len(content) > len(content_stripped)
  1207. else ""
  1208. )
  1209. return content_stripped, original_whitespace
  1210. def is_opening_code_block(content):
  1211. backtick_segments = content.split("```")
  1212. # Even number of segments means the last backticks are opening a new block
  1213. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  1214. # Handle as a background task
  1215. async def response_handler(response, events):
  1216. def serialize_content_blocks(content_blocks, raw=False):
  1217. content = ""
  1218. for block in content_blocks:
  1219. if block["type"] == "text":
  1220. block_content = block["content"].strip()
  1221. if block_content:
  1222. content = f"{content}{block_content}\n"
  1223. elif block["type"] == "tool_calls":
  1224. attributes = block.get("attributes", {})
  1225. tool_calls = block.get("content", [])
  1226. results = block.get("results", [])
  1227. if content and not content.endswith("\n"):
  1228. content += "\n"
  1229. if results:
  1230. tool_calls_display_content = ""
  1231. for tool_call in tool_calls:
  1232. tool_call_id = tool_call.get("id", "")
  1233. tool_name = tool_call.get("function", {}).get(
  1234. "name", ""
  1235. )
  1236. tool_arguments = tool_call.get("function", {}).get(
  1237. "arguments", ""
  1238. )
  1239. tool_result = None
  1240. tool_result_files = None
  1241. for result in results:
  1242. if tool_call_id == result.get("tool_call_id", ""):
  1243. tool_result = result.get("content", None)
  1244. tool_result_files = result.get("files", None)
  1245. break
  1246. if tool_result:
  1247. tool_calls_display_content = f'{tool_calls_display_content}<details type="tool_calls" done="true" id="{tool_call_id}" name="{tool_name}" arguments="{html.escape(json.dumps(tool_arguments))}" result="{html.escape(json.dumps(tool_result, ensure_ascii=False))}" files="{html.escape(json.dumps(tool_result_files)) if tool_result_files else ""}">\n<summary>Tool Executed</summary>\n</details>\n'
  1248. else:
  1249. tool_calls_display_content = f'{tool_calls_display_content}<details type="tool_calls" done="false" id="{tool_call_id}" name="{tool_name}" arguments="{html.escape(json.dumps(tool_arguments))}">\n<summary>Executing...</summary>\n</details>\n'
  1250. if not raw:
  1251. content = f"{content}{tool_calls_display_content}"
  1252. else:
  1253. tool_calls_display_content = ""
  1254. for tool_call in tool_calls:
  1255. tool_call_id = tool_call.get("id", "")
  1256. tool_name = tool_call.get("function", {}).get(
  1257. "name", ""
  1258. )
  1259. tool_arguments = tool_call.get("function", {}).get(
  1260. "arguments", ""
  1261. )
  1262. tool_calls_display_content = f'{tool_calls_display_content}\n<details type="tool_calls" done="false" id="{tool_call_id}" name="{tool_name}" arguments="{html.escape(json.dumps(tool_arguments))}">\n<summary>Executing...</summary>\n</details>\n'
  1263. if not raw:
  1264. content = f"{content}{tool_calls_display_content}"
  1265. elif block["type"] == "reasoning":
  1266. reasoning_display_content = "\n".join(
  1267. (f"> {line}" if not line.startswith(">") else line)
  1268. for line in block["content"].splitlines()
  1269. )
  1270. reasoning_duration = block.get("duration", None)
  1271. start_tag = block.get("start_tag", "")
  1272. end_tag = block.get("end_tag", "")
  1273. if content and not content.endswith("\n"):
  1274. content += "\n"
  1275. if reasoning_duration is not None:
  1276. if raw:
  1277. content = (
  1278. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1279. )
  1280. else:
  1281. content = f'{content}<details type="reasoning" done="true" duration="{reasoning_duration}">\n<summary>Thought for {reasoning_duration} seconds</summary>\n{reasoning_display_content}\n</details>\n'
  1282. else:
  1283. if raw:
  1284. content = (
  1285. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1286. )
  1287. else:
  1288. content = f'{content}<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1289. elif block["type"] == "code_interpreter":
  1290. attributes = block.get("attributes", {})
  1291. output = block.get("output", None)
  1292. lang = attributes.get("lang", "")
  1293. content_stripped, original_whitespace = (
  1294. split_content_and_whitespace(content)
  1295. )
  1296. if is_opening_code_block(content_stripped):
  1297. # Remove trailing backticks that would open a new block
  1298. content = (
  1299. content_stripped.rstrip("`").rstrip()
  1300. + original_whitespace
  1301. )
  1302. else:
  1303. # Keep content as is - either closing backticks or no backticks
  1304. content = content_stripped + original_whitespace
  1305. if content and not content.endswith("\n"):
  1306. content += "\n"
  1307. if output:
  1308. output = html.escape(json.dumps(output))
  1309. if raw:
  1310. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1311. else:
  1312. content = f'{content}<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1313. else:
  1314. if raw:
  1315. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1316. else:
  1317. content = f'{content}<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1318. else:
  1319. block_content = str(block["content"]).strip()
  1320. if block_content:
  1321. content = f"{content}{block['type']}: {block_content}\n"
  1322. return content.strip()
  1323. def convert_content_blocks_to_messages(content_blocks, raw=False):
  1324. messages = []
  1325. temp_blocks = []
  1326. for idx, block in enumerate(content_blocks):
  1327. if block["type"] == "tool_calls":
  1328. messages.append(
  1329. {
  1330. "role": "assistant",
  1331. "content": serialize_content_blocks(temp_blocks, raw),
  1332. "tool_calls": block.get("content"),
  1333. }
  1334. )
  1335. results = block.get("results", [])
  1336. for result in results:
  1337. messages.append(
  1338. {
  1339. "role": "tool",
  1340. "tool_call_id": result["tool_call_id"],
  1341. "content": result["content"],
  1342. }
  1343. )
  1344. temp_blocks = []
  1345. else:
  1346. temp_blocks.append(block)
  1347. if temp_blocks:
  1348. content = serialize_content_blocks(temp_blocks, raw)
  1349. if content:
  1350. messages.append(
  1351. {
  1352. "role": "assistant",
  1353. "content": content,
  1354. }
  1355. )
  1356. return messages
  1357. def tag_content_handler(content_type, tags, content, content_blocks):
  1358. end_flag = False
  1359. def extract_attributes(tag_content):
  1360. """Extract attributes from a tag if they exist."""
  1361. attributes = {}
  1362. if not tag_content: # Ensure tag_content is not None
  1363. return attributes
  1364. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1365. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1366. for key, value in matches:
  1367. attributes[key] = value
  1368. return attributes
  1369. if content_blocks[-1]["type"] == "text":
  1370. for start_tag, end_tag in tags:
  1371. start_tag_pattern = rf"{re.escape(start_tag)}"
  1372. if start_tag.startswith("<") and start_tag.endswith(">"):
  1373. # Match start tag e.g., <tag> or <tag attr="value">
  1374. # remove both '<' and '>' from start_tag
  1375. # Match start tag with attributes
  1376. start_tag_pattern = (
  1377. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1378. )
  1379. match = re.search(start_tag_pattern, content)
  1380. if match:
  1381. try:
  1382. attr_content = (
  1383. match.group(1) if match.group(1) else ""
  1384. ) # Ensure it's not None
  1385. except:
  1386. attr_content = ""
  1387. attributes = extract_attributes(
  1388. attr_content
  1389. ) # Extract attributes safely
  1390. # Capture everything before and after the matched tag
  1391. before_tag = content[
  1392. : match.start()
  1393. ] # Content before opening tag
  1394. after_tag = content[
  1395. match.end() :
  1396. ] # Content after opening tag
  1397. # Remove the start tag and after from the currently handling text block
  1398. content_blocks[-1]["content"] = content_blocks[-1][
  1399. "content"
  1400. ].replace(match.group(0) + after_tag, "")
  1401. if before_tag:
  1402. content_blocks[-1]["content"] = before_tag
  1403. if not content_blocks[-1]["content"]:
  1404. content_blocks.pop()
  1405. # Append the new block
  1406. content_blocks.append(
  1407. {
  1408. "type": content_type,
  1409. "start_tag": start_tag,
  1410. "end_tag": end_tag,
  1411. "attributes": attributes,
  1412. "content": "",
  1413. "started_at": time.time(),
  1414. }
  1415. )
  1416. if after_tag:
  1417. content_blocks[-1]["content"] = after_tag
  1418. tag_content_handler(
  1419. content_type, tags, after_tag, content_blocks
  1420. )
  1421. break
  1422. elif content_blocks[-1]["type"] == content_type:
  1423. start_tag = content_blocks[-1]["start_tag"]
  1424. end_tag = content_blocks[-1]["end_tag"]
  1425. if end_tag.startswith("<") and end_tag.endswith(">"):
  1426. # Match end tag e.g., </tag>
  1427. end_tag_pattern = rf"{re.escape(end_tag)}"
  1428. else:
  1429. # Handle cases where end_tag is just a tag name
  1430. end_tag_pattern = rf"{re.escape(end_tag)}"
  1431. # Check if the content has the end tag
  1432. if re.search(end_tag_pattern, content):
  1433. end_flag = True
  1434. block_content = content_blocks[-1]["content"]
  1435. # Strip start and end tags from the content
  1436. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1437. block_content = re.sub(
  1438. start_tag_pattern, "", block_content
  1439. ).strip()
  1440. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1441. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1442. # Content inside the tag
  1443. block_content = (
  1444. split_content[0].strip() if split_content else ""
  1445. )
  1446. # Leftover content (everything after `</tag>`)
  1447. leftover_content = (
  1448. split_content[1].strip() if len(split_content) > 1 else ""
  1449. )
  1450. if block_content:
  1451. content_blocks[-1]["content"] = block_content
  1452. content_blocks[-1]["ended_at"] = time.time()
  1453. content_blocks[-1]["duration"] = int(
  1454. content_blocks[-1]["ended_at"]
  1455. - content_blocks[-1]["started_at"]
  1456. )
  1457. # Reset the content_blocks by appending a new text block
  1458. if content_type != "code_interpreter":
  1459. if leftover_content:
  1460. content_blocks.append(
  1461. {
  1462. "type": "text",
  1463. "content": leftover_content,
  1464. }
  1465. )
  1466. else:
  1467. content_blocks.append(
  1468. {
  1469. "type": "text",
  1470. "content": "",
  1471. }
  1472. )
  1473. else:
  1474. # Remove the block if content is empty
  1475. content_blocks.pop()
  1476. if leftover_content:
  1477. content_blocks.append(
  1478. {
  1479. "type": "text",
  1480. "content": leftover_content,
  1481. }
  1482. )
  1483. else:
  1484. content_blocks.append(
  1485. {
  1486. "type": "text",
  1487. "content": "",
  1488. }
  1489. )
  1490. # Clean processed content
  1491. start_tag_pattern = rf"{re.escape(start_tag)}"
  1492. if start_tag.startswith("<") and start_tag.endswith(">"):
  1493. # Match start tag e.g., <tag> or <tag attr="value">
  1494. # remove both '<' and '>' from start_tag
  1495. # Match start tag with attributes
  1496. start_tag_pattern = (
  1497. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1498. )
  1499. content = re.sub(
  1500. rf"{start_tag_pattern}(.|\n)*?{re.escape(end_tag)}",
  1501. "",
  1502. content,
  1503. flags=re.DOTALL,
  1504. )
  1505. return content, content_blocks, end_flag
  1506. message = Chats.get_message_by_id_and_message_id(
  1507. metadata["chat_id"], metadata["message_id"]
  1508. )
  1509. tool_calls = []
  1510. last_assistant_message = None
  1511. try:
  1512. if form_data["messages"][-1]["role"] == "assistant":
  1513. last_assistant_message = get_last_assistant_message(
  1514. form_data["messages"]
  1515. )
  1516. except Exception as e:
  1517. pass
  1518. content = (
  1519. message.get("content", "")
  1520. if message
  1521. else last_assistant_message if last_assistant_message else ""
  1522. )
  1523. content_blocks = [
  1524. {
  1525. "type": "text",
  1526. "content": content,
  1527. }
  1528. ]
  1529. # We might want to disable this by default
  1530. DETECT_REASONING = True
  1531. DETECT_SOLUTION = True
  1532. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1533. "code_interpreter", False
  1534. )
  1535. reasoning_tags = [
  1536. ("<think>", "</think>"),
  1537. ("<thinking>", "</thinking>"),
  1538. ("<reason>", "</reason>"),
  1539. ("<reasoning>", "</reasoning>"),
  1540. ("<thought>", "</thought>"),
  1541. ("<Thought>", "</Thought>"),
  1542. ("<|begin_of_thought|>", "<|end_of_thought|>"),
  1543. ("◁think▷", "◁/think▷"),
  1544. ]
  1545. code_interpreter_tags = [("<code_interpreter>", "</code_interpreter>")]
  1546. solution_tags = [("<|begin_of_solution|>", "<|end_of_solution|>")]
  1547. try:
  1548. for event in events:
  1549. await event_emitter(
  1550. {
  1551. "type": "chat:completion",
  1552. "data": event,
  1553. }
  1554. )
  1555. # Save message in the database
  1556. Chats.upsert_message_to_chat_by_id_and_message_id(
  1557. metadata["chat_id"],
  1558. metadata["message_id"],
  1559. {
  1560. **event,
  1561. },
  1562. )
  1563. async def stream_body_handler(response, form_data):
  1564. nonlocal content
  1565. nonlocal content_blocks
  1566. response_tool_calls = []
  1567. delta_count = 0
  1568. delta_chunk_size = max(
  1569. CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
  1570. int(
  1571. metadata.get("params", {}).get("stream_delta_chunk_size")
  1572. or 1
  1573. ),
  1574. )
  1575. last_delta_data = None
  1576. async def flush_pending_delta_data(threshold: int = 0):
  1577. nonlocal delta_count
  1578. nonlocal last_delta_data
  1579. if delta_count >= threshold and last_delta_data:
  1580. await event_emitter(
  1581. {
  1582. "type": "chat:completion",
  1583. "data": last_delta_data,
  1584. }
  1585. )
  1586. delta_count = 0
  1587. last_delta_data = None
  1588. async for line in response.body_iterator:
  1589. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1590. data = line
  1591. # Skip empty lines
  1592. if not data.strip():
  1593. continue
  1594. # "data:" is the prefix for each event
  1595. if not data.startswith("data:"):
  1596. continue
  1597. # Remove the prefix
  1598. data = data[len("data:") :].strip()
  1599. try:
  1600. data = json.loads(data)
  1601. data, _ = await process_filter_functions(
  1602. request=request,
  1603. filter_functions=filter_functions,
  1604. filter_type="stream",
  1605. form_data=data,
  1606. extra_params={"__body__": form_data, **extra_params},
  1607. )
  1608. if data:
  1609. if "event" in data:
  1610. await event_emitter(data.get("event", {}))
  1611. if "selected_model_id" in data:
  1612. model_id = data["selected_model_id"]
  1613. Chats.upsert_message_to_chat_by_id_and_message_id(
  1614. metadata["chat_id"],
  1615. metadata["message_id"],
  1616. {
  1617. "selectedModelId": model_id,
  1618. },
  1619. )
  1620. await event_emitter(
  1621. {
  1622. "type": "chat:completion",
  1623. "data": data,
  1624. }
  1625. )
  1626. else:
  1627. choices = data.get("choices", [])
  1628. if not choices:
  1629. error = data.get("error", {})
  1630. if error:
  1631. await event_emitter(
  1632. {
  1633. "type": "chat:completion",
  1634. "data": {
  1635. "error": error,
  1636. },
  1637. }
  1638. )
  1639. usage = data.get("usage", {})
  1640. if usage:
  1641. await event_emitter(
  1642. {
  1643. "type": "chat:completion",
  1644. "data": {
  1645. "usage": usage,
  1646. },
  1647. }
  1648. )
  1649. continue
  1650. delta = choices[0].get("delta", {})
  1651. delta_tool_calls = delta.get("tool_calls", None)
  1652. if delta_tool_calls:
  1653. for delta_tool_call in delta_tool_calls:
  1654. tool_call_index = delta_tool_call.get(
  1655. "index"
  1656. )
  1657. if tool_call_index is not None:
  1658. # Check if the tool call already exists
  1659. current_response_tool_call = None
  1660. for (
  1661. response_tool_call
  1662. ) in response_tool_calls:
  1663. if (
  1664. response_tool_call.get("index")
  1665. == tool_call_index
  1666. ):
  1667. current_response_tool_call = (
  1668. response_tool_call
  1669. )
  1670. break
  1671. if current_response_tool_call is None:
  1672. # Add the new tool call
  1673. delta_tool_call.setdefault(
  1674. "function", {}
  1675. )
  1676. delta_tool_call[
  1677. "function"
  1678. ].setdefault("name", "")
  1679. delta_tool_call[
  1680. "function"
  1681. ].setdefault("arguments", "")
  1682. response_tool_calls.append(
  1683. delta_tool_call
  1684. )
  1685. else:
  1686. # Update the existing tool call
  1687. delta_name = delta_tool_call.get(
  1688. "function", {}
  1689. ).get("name")
  1690. delta_arguments = (
  1691. delta_tool_call.get(
  1692. "function", {}
  1693. ).get("arguments")
  1694. )
  1695. if delta_name:
  1696. current_response_tool_call[
  1697. "function"
  1698. ]["name"] += delta_name
  1699. if delta_arguments:
  1700. current_response_tool_call[
  1701. "function"
  1702. ][
  1703. "arguments"
  1704. ] += delta_arguments
  1705. value = delta.get("content")
  1706. reasoning_content = (
  1707. delta.get("reasoning_content")
  1708. or delta.get("reasoning")
  1709. or delta.get("thinking")
  1710. )
  1711. if reasoning_content:
  1712. if (
  1713. not content_blocks
  1714. or content_blocks[-1]["type"] != "reasoning"
  1715. ):
  1716. reasoning_block = {
  1717. "type": "reasoning",
  1718. "start_tag": "<think>",
  1719. "end_tag": "</think>",
  1720. "attributes": {
  1721. "type": "reasoning_content"
  1722. },
  1723. "content": "",
  1724. "started_at": time.time(),
  1725. }
  1726. content_blocks.append(reasoning_block)
  1727. else:
  1728. reasoning_block = content_blocks[-1]
  1729. reasoning_block["content"] += reasoning_content
  1730. data = {
  1731. "content": serialize_content_blocks(
  1732. content_blocks
  1733. )
  1734. }
  1735. if value:
  1736. if (
  1737. content_blocks
  1738. and content_blocks[-1]["type"]
  1739. == "reasoning"
  1740. and content_blocks[-1]
  1741. .get("attributes", {})
  1742. .get("type")
  1743. == "reasoning_content"
  1744. ):
  1745. reasoning_block = content_blocks[-1]
  1746. reasoning_block["ended_at"] = time.time()
  1747. reasoning_block["duration"] = int(
  1748. reasoning_block["ended_at"]
  1749. - reasoning_block["started_at"]
  1750. )
  1751. content_blocks.append(
  1752. {
  1753. "type": "text",
  1754. "content": "",
  1755. }
  1756. )
  1757. content = f"{content}{value}"
  1758. if not content_blocks:
  1759. content_blocks.append(
  1760. {
  1761. "type": "text",
  1762. "content": "",
  1763. }
  1764. )
  1765. content_blocks[-1]["content"] = (
  1766. content_blocks[-1]["content"] + value
  1767. )
  1768. if DETECT_REASONING:
  1769. content, content_blocks, _ = (
  1770. tag_content_handler(
  1771. "reasoning",
  1772. reasoning_tags,
  1773. content,
  1774. content_blocks,
  1775. )
  1776. )
  1777. if DETECT_CODE_INTERPRETER:
  1778. content, content_blocks, end = (
  1779. tag_content_handler(
  1780. "code_interpreter",
  1781. code_interpreter_tags,
  1782. content,
  1783. content_blocks,
  1784. )
  1785. )
  1786. if end:
  1787. break
  1788. if DETECT_SOLUTION:
  1789. content, content_blocks, _ = (
  1790. tag_content_handler(
  1791. "solution",
  1792. solution_tags,
  1793. content,
  1794. content_blocks,
  1795. )
  1796. )
  1797. if ENABLE_REALTIME_CHAT_SAVE:
  1798. # Save message in the database
  1799. Chats.upsert_message_to_chat_by_id_and_message_id(
  1800. metadata["chat_id"],
  1801. metadata["message_id"],
  1802. {
  1803. "content": serialize_content_blocks(
  1804. content_blocks
  1805. ),
  1806. },
  1807. )
  1808. else:
  1809. data = {
  1810. "content": serialize_content_blocks(
  1811. content_blocks
  1812. ),
  1813. }
  1814. if delta:
  1815. delta_count += 1
  1816. last_delta_data = data
  1817. if delta_count >= delta_chunk_size:
  1818. await flush_pending_delta_data(delta_chunk_size)
  1819. else:
  1820. await event_emitter(
  1821. {
  1822. "type": "chat:completion",
  1823. "data": data,
  1824. }
  1825. )
  1826. except Exception as e:
  1827. done = "data: [DONE]" in line
  1828. if done:
  1829. pass
  1830. else:
  1831. log.debug(f"Error: {e}")
  1832. continue
  1833. await flush_pending_delta_data()
  1834. if content_blocks:
  1835. # Clean up the last text block
  1836. if content_blocks[-1]["type"] == "text":
  1837. content_blocks[-1]["content"] = content_blocks[-1][
  1838. "content"
  1839. ].strip()
  1840. if not content_blocks[-1]["content"]:
  1841. content_blocks.pop()
  1842. if not content_blocks:
  1843. content_blocks.append(
  1844. {
  1845. "type": "text",
  1846. "content": "",
  1847. }
  1848. )
  1849. if content_blocks[-1]["type"] == "reasoning":
  1850. reasoning_block = content_blocks[-1]
  1851. if reasoning_block.get("ended_at") is None:
  1852. reasoning_block["ended_at"] = time.time()
  1853. reasoning_block["duration"] = int(
  1854. reasoning_block["ended_at"]
  1855. - reasoning_block["started_at"]
  1856. )
  1857. if response_tool_calls:
  1858. tool_calls.append(response_tool_calls)
  1859. if response.background:
  1860. await response.background()
  1861. await stream_body_handler(response, form_data)
  1862. MAX_TOOL_CALL_RETRIES = 10
  1863. tool_call_retries = 0
  1864. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1865. tool_call_retries += 1
  1866. response_tool_calls = tool_calls.pop(0)
  1867. content_blocks.append(
  1868. {
  1869. "type": "tool_calls",
  1870. "content": response_tool_calls,
  1871. }
  1872. )
  1873. await event_emitter(
  1874. {
  1875. "type": "chat:completion",
  1876. "data": {
  1877. "content": serialize_content_blocks(content_blocks),
  1878. },
  1879. }
  1880. )
  1881. tools = metadata.get("tools", {})
  1882. results = []
  1883. for tool_call in response_tool_calls:
  1884. tool_call_id = tool_call.get("id", "")
  1885. tool_name = tool_call.get("function", {}).get("name", "")
  1886. tool_args = tool_call.get("function", {}).get("arguments", "{}")
  1887. tool_function_params = {}
  1888. try:
  1889. # json.loads cannot be used because some models do not produce valid JSON
  1890. tool_function_params = ast.literal_eval(tool_args)
  1891. except Exception as e:
  1892. log.debug(e)
  1893. # Fallback to JSON parsing
  1894. try:
  1895. tool_function_params = json.loads(tool_args)
  1896. except Exception as e:
  1897. log.error(
  1898. f"Error parsing tool call arguments: {tool_args}"
  1899. )
  1900. # Mutate the original tool call response params as they are passed back to the passed
  1901. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  1902. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  1903. # params are not valid json.
  1904. # Main case so far is no args = "" = invalid json.
  1905. log.debug(
  1906. f"Parsed args from {tool_args} to {tool_function_params}"
  1907. )
  1908. tool_call.setdefault("function", {})["arguments"] = json.dumps(
  1909. tool_function_params
  1910. )
  1911. tool_result = None
  1912. if tool_name in tools:
  1913. tool = tools[tool_name]
  1914. spec = tool.get("spec", {})
  1915. try:
  1916. allowed_params = (
  1917. spec.get("parameters", {})
  1918. .get("properties", {})
  1919. .keys()
  1920. )
  1921. tool_function_params = {
  1922. k: v
  1923. for k, v in tool_function_params.items()
  1924. if k in allowed_params
  1925. }
  1926. if tool.get("direct", False):
  1927. tool_result = await event_caller(
  1928. {
  1929. "type": "execute:tool",
  1930. "data": {
  1931. "id": str(uuid4()),
  1932. "name": tool_name,
  1933. "params": tool_function_params,
  1934. "server": tool.get("server", {}),
  1935. "session_id": metadata.get(
  1936. "session_id", None
  1937. ),
  1938. },
  1939. }
  1940. )
  1941. else:
  1942. tool_function = tool["callable"]
  1943. tool_result = await tool_function(
  1944. **tool_function_params
  1945. )
  1946. except Exception as e:
  1947. tool_result = str(e)
  1948. tool_result_files = []
  1949. if isinstance(tool_result, list):
  1950. for item in tool_result:
  1951. # check if string
  1952. if isinstance(item, str) and item.startswith("data:"):
  1953. tool_result_files.append(item)
  1954. tool_result.remove(item)
  1955. if isinstance(tool_result, dict) or isinstance(
  1956. tool_result, list
  1957. ):
  1958. tool_result = json.dumps(
  1959. tool_result, indent=2, ensure_ascii=False
  1960. )
  1961. results.append(
  1962. {
  1963. "tool_call_id": tool_call_id,
  1964. "content": tool_result,
  1965. **(
  1966. {"files": tool_result_files}
  1967. if tool_result_files
  1968. else {}
  1969. ),
  1970. }
  1971. )
  1972. content_blocks[-1]["results"] = results
  1973. content_blocks.append(
  1974. {
  1975. "type": "text",
  1976. "content": "",
  1977. }
  1978. )
  1979. await event_emitter(
  1980. {
  1981. "type": "chat:completion",
  1982. "data": {
  1983. "content": serialize_content_blocks(content_blocks),
  1984. },
  1985. }
  1986. )
  1987. try:
  1988. new_form_data = {
  1989. "model": model_id,
  1990. "stream": True,
  1991. "tools": form_data["tools"],
  1992. "messages": [
  1993. *form_data["messages"],
  1994. *convert_content_blocks_to_messages(
  1995. content_blocks, True
  1996. ),
  1997. ],
  1998. }
  1999. res = await generate_chat_completion(
  2000. request,
  2001. new_form_data,
  2002. user,
  2003. )
  2004. if isinstance(res, StreamingResponse):
  2005. await stream_body_handler(res, new_form_data)
  2006. else:
  2007. break
  2008. except Exception as e:
  2009. log.debug(e)
  2010. break
  2011. if DETECT_CODE_INTERPRETER:
  2012. MAX_RETRIES = 5
  2013. retries = 0
  2014. while (
  2015. content_blocks[-1]["type"] == "code_interpreter"
  2016. and retries < MAX_RETRIES
  2017. ):
  2018. await event_emitter(
  2019. {
  2020. "type": "chat:completion",
  2021. "data": {
  2022. "content": serialize_content_blocks(content_blocks),
  2023. },
  2024. }
  2025. )
  2026. retries += 1
  2027. log.debug(f"Attempt count: {retries}")
  2028. output = ""
  2029. try:
  2030. if content_blocks[-1]["attributes"].get("type") == "code":
  2031. code = content_blocks[-1]["content"]
  2032. if CODE_INTERPRETER_BLOCKED_MODULES:
  2033. blocking_code = textwrap.dedent(
  2034. f"""
  2035. import builtins
  2036. BLOCKED_MODULES = {CODE_INTERPRETER_BLOCKED_MODULES}
  2037. _real_import = builtins.__import__
  2038. def restricted_import(name, globals=None, locals=None, fromlist=(), level=0):
  2039. if name.split('.')[0] in BLOCKED_MODULES:
  2040. importer_name = globals.get('__name__') if globals else None
  2041. if importer_name == '__main__':
  2042. raise ImportError(
  2043. f"Direct import of module {{name}} is restricted."
  2044. )
  2045. return _real_import(name, globals, locals, fromlist, level)
  2046. builtins.__import__ = restricted_import
  2047. """
  2048. )
  2049. code = blocking_code + "\n" + code
  2050. if (
  2051. request.app.state.config.CODE_INTERPRETER_ENGINE
  2052. == "pyodide"
  2053. ):
  2054. output = await event_caller(
  2055. {
  2056. "type": "execute:python",
  2057. "data": {
  2058. "id": str(uuid4()),
  2059. "code": code,
  2060. "session_id": metadata.get(
  2061. "session_id", None
  2062. ),
  2063. },
  2064. }
  2065. )
  2066. elif (
  2067. request.app.state.config.CODE_INTERPRETER_ENGINE
  2068. == "jupyter"
  2069. ):
  2070. output = await execute_code_jupyter(
  2071. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  2072. code,
  2073. (
  2074. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  2075. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2076. == "token"
  2077. else None
  2078. ),
  2079. (
  2080. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  2081. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2082. == "password"
  2083. else None
  2084. ),
  2085. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  2086. )
  2087. else:
  2088. output = {
  2089. "stdout": "Code interpreter engine not configured."
  2090. }
  2091. log.debug(f"Code interpreter output: {output}")
  2092. if isinstance(output, dict):
  2093. stdout = output.get("stdout", "")
  2094. if isinstance(stdout, str):
  2095. stdoutLines = stdout.split("\n")
  2096. for idx, line in enumerate(stdoutLines):
  2097. if "data:image/png;base64" in line:
  2098. image_url = ""
  2099. # Extract base64 image data from the line
  2100. image_data, content_type = (
  2101. load_b64_image_data(line)
  2102. )
  2103. if image_data is not None:
  2104. image_url = upload_image(
  2105. request,
  2106. image_data,
  2107. content_type,
  2108. metadata,
  2109. user,
  2110. )
  2111. stdoutLines[idx] = (
  2112. f"![Output Image]({image_url})"
  2113. )
  2114. output["stdout"] = "\n".join(stdoutLines)
  2115. result = output.get("result", "")
  2116. if isinstance(result, str):
  2117. resultLines = result.split("\n")
  2118. for idx, line in enumerate(resultLines):
  2119. if "data:image/png;base64" in line:
  2120. image_url = ""
  2121. # Extract base64 image data from the line
  2122. image_data, content_type = (
  2123. load_b64_image_data(line)
  2124. )
  2125. if image_data is not None:
  2126. image_url = upload_image(
  2127. request,
  2128. image_data,
  2129. content_type,
  2130. metadata,
  2131. user,
  2132. )
  2133. resultLines[idx] = (
  2134. f"![Output Image]({image_url})"
  2135. )
  2136. output["result"] = "\n".join(resultLines)
  2137. except Exception as e:
  2138. output = str(e)
  2139. content_blocks[-1]["output"] = output
  2140. content_blocks.append(
  2141. {
  2142. "type": "text",
  2143. "content": "",
  2144. }
  2145. )
  2146. await event_emitter(
  2147. {
  2148. "type": "chat:completion",
  2149. "data": {
  2150. "content": serialize_content_blocks(content_blocks),
  2151. },
  2152. }
  2153. )
  2154. try:
  2155. new_form_data = {
  2156. "model": model_id,
  2157. "stream": True,
  2158. "messages": [
  2159. *form_data["messages"],
  2160. {
  2161. "role": "assistant",
  2162. "content": serialize_content_blocks(
  2163. content_blocks, raw=True
  2164. ),
  2165. },
  2166. ],
  2167. }
  2168. res = await generate_chat_completion(
  2169. request,
  2170. new_form_data,
  2171. user,
  2172. )
  2173. if isinstance(res, StreamingResponse):
  2174. await stream_body_handler(res, new_form_data)
  2175. else:
  2176. break
  2177. except Exception as e:
  2178. log.debug(e)
  2179. break
  2180. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  2181. data = {
  2182. "done": True,
  2183. "content": serialize_content_blocks(content_blocks),
  2184. "title": title,
  2185. }
  2186. if not ENABLE_REALTIME_CHAT_SAVE:
  2187. # Save message in the database
  2188. Chats.upsert_message_to_chat_by_id_and_message_id(
  2189. metadata["chat_id"],
  2190. metadata["message_id"],
  2191. {
  2192. "content": serialize_content_blocks(content_blocks),
  2193. },
  2194. )
  2195. # Send a webhook notification if the user is not active
  2196. if not get_active_status_by_user_id(user.id):
  2197. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  2198. if webhook_url:
  2199. await post_webhook(
  2200. request.app.state.WEBUI_NAME,
  2201. webhook_url,
  2202. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  2203. {
  2204. "action": "chat",
  2205. "message": content,
  2206. "title": title,
  2207. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  2208. },
  2209. )
  2210. await event_emitter(
  2211. {
  2212. "type": "chat:completion",
  2213. "data": data,
  2214. }
  2215. )
  2216. await background_tasks_handler()
  2217. except asyncio.CancelledError:
  2218. log.warning("Task was cancelled!")
  2219. await event_emitter({"type": "task-cancelled"})
  2220. if not ENABLE_REALTIME_CHAT_SAVE:
  2221. # Save message in the database
  2222. Chats.upsert_message_to_chat_by_id_and_message_id(
  2223. metadata["chat_id"],
  2224. metadata["message_id"],
  2225. {
  2226. "content": serialize_content_blocks(content_blocks),
  2227. },
  2228. )
  2229. if response.background is not None:
  2230. await response.background()
  2231. return await response_handler(response, events)
  2232. else:
  2233. # Fallback to the original response
  2234. async def stream_wrapper(original_generator, events):
  2235. def wrap_item(item):
  2236. return f"data: {item}\n\n"
  2237. for event in events:
  2238. event, _ = await process_filter_functions(
  2239. request=request,
  2240. filter_functions=filter_functions,
  2241. filter_type="stream",
  2242. form_data=event,
  2243. extra_params=extra_params,
  2244. )
  2245. if event:
  2246. yield wrap_item(json.dumps(event))
  2247. async for data in original_generator:
  2248. data, _ = await process_filter_functions(
  2249. request=request,
  2250. filter_functions=filter_functions,
  2251. filter_type="stream",
  2252. form_data=data,
  2253. extra_params=extra_params,
  2254. )
  2255. if data:
  2256. yield data
  2257. return StreamingResponse(
  2258. stream_wrapper(response.body_iterator, events),
  2259. headers=dict(response.headers),
  2260. background=response.background,
  2261. )