middleware.py 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648
  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. try:
  625. form_data = apply_system_prompt_to_body(
  626. system_message.get("content"), form_data, metadata, user
  627. )
  628. except:
  629. pass
  630. event_emitter = get_event_emitter(metadata)
  631. event_call = get_event_call(metadata)
  632. extra_params = {
  633. "__event_emitter__": event_emitter,
  634. "__event_call__": event_call,
  635. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  636. "__metadata__": metadata,
  637. "__request__": request,
  638. "__model__": model,
  639. }
  640. # Initialize events to store additional event to be sent to the client
  641. # Initialize contexts and citation
  642. if getattr(request.state, "direct", False) and hasattr(request.state, "model"):
  643. models = {
  644. request.state.model["id"]: request.state.model,
  645. }
  646. else:
  647. models = request.app.state.MODELS
  648. task_model_id = get_task_model_id(
  649. form_data["model"],
  650. request.app.state.config.TASK_MODEL,
  651. request.app.state.config.TASK_MODEL_EXTERNAL,
  652. models,
  653. )
  654. events = []
  655. sources = []
  656. # Folder "Project" handling
  657. # Check if the request has chat_id and is inside of a folder
  658. chat_id = metadata.get("chat_id", None)
  659. if chat_id and user:
  660. chat = Chats.get_chat_by_id_and_user_id(chat_id, user.id)
  661. if chat and chat.folder_id:
  662. folder = Folders.get_folder_by_id_and_user_id(chat.folder_id, user.id)
  663. if folder and folder.data:
  664. if "system_prompt" in folder.data:
  665. form_data = apply_system_prompt_to_body(
  666. folder.data["system_prompt"], form_data, metadata, user
  667. )
  668. if "files" in folder.data:
  669. form_data["files"] = [
  670. *folder.data["files"],
  671. *form_data.get("files", []),
  672. ]
  673. # Model "Knowledge" handling
  674. user_message = get_last_user_message(form_data["messages"])
  675. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  676. if model_knowledge:
  677. await event_emitter(
  678. {
  679. "type": "status",
  680. "data": {
  681. "action": "knowledge_search",
  682. "query": user_message,
  683. "done": False,
  684. },
  685. }
  686. )
  687. knowledge_files = []
  688. for item in model_knowledge:
  689. if item.get("collection_name"):
  690. knowledge_files.append(
  691. {
  692. "id": item.get("collection_name"),
  693. "name": item.get("name"),
  694. "legacy": True,
  695. }
  696. )
  697. elif item.get("collection_names"):
  698. knowledge_files.append(
  699. {
  700. "name": item.get("name"),
  701. "type": "collection",
  702. "collection_names": item.get("collection_names"),
  703. "legacy": True,
  704. }
  705. )
  706. else:
  707. knowledge_files.append(item)
  708. files = form_data.get("files", [])
  709. files.extend(knowledge_files)
  710. form_data["files"] = files
  711. variables = form_data.pop("variables", None)
  712. # Process the form_data through the pipeline
  713. try:
  714. form_data = await process_pipeline_inlet_filter(
  715. request, form_data, user, models
  716. )
  717. except Exception as e:
  718. raise e
  719. try:
  720. filter_functions = [
  721. Functions.get_function_by_id(filter_id)
  722. for filter_id in get_sorted_filter_ids(
  723. request, model, metadata.get("filter_ids", [])
  724. )
  725. ]
  726. form_data, flags = await process_filter_functions(
  727. request=request,
  728. filter_functions=filter_functions,
  729. filter_type="inlet",
  730. form_data=form_data,
  731. extra_params=extra_params,
  732. )
  733. except Exception as e:
  734. raise Exception(f"Error: {e}")
  735. features = form_data.pop("features", None)
  736. if features:
  737. if "memory" in features and features["memory"]:
  738. form_data = await chat_memory_handler(
  739. request, form_data, extra_params, user
  740. )
  741. if "web_search" in features and features["web_search"]:
  742. form_data = await chat_web_search_handler(
  743. request, form_data, extra_params, user
  744. )
  745. if "image_generation" in features and features["image_generation"]:
  746. form_data = await chat_image_generation_handler(
  747. request, form_data, extra_params, user
  748. )
  749. if "code_interpreter" in features and features["code_interpreter"]:
  750. form_data["messages"] = add_or_update_user_message(
  751. (
  752. request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE
  753. if request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE != ""
  754. else DEFAULT_CODE_INTERPRETER_PROMPT
  755. ),
  756. form_data["messages"],
  757. )
  758. tool_ids = form_data.pop("tool_ids", None)
  759. files = form_data.pop("files", None)
  760. # Remove files duplicates
  761. if files:
  762. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  763. metadata = {
  764. **metadata,
  765. "tool_ids": tool_ids,
  766. "files": files,
  767. }
  768. form_data["metadata"] = metadata
  769. # Server side tools
  770. tool_ids = metadata.get("tool_ids", None)
  771. # Client side tools
  772. tool_servers = metadata.get("tool_servers", None)
  773. log.debug(f"{tool_ids=}")
  774. log.debug(f"{tool_servers=}")
  775. tools_dict = {}
  776. if tool_ids:
  777. tools_dict = await get_tools(
  778. request,
  779. tool_ids,
  780. user,
  781. {
  782. **extra_params,
  783. "__model__": models[task_model_id],
  784. "__messages__": form_data["messages"],
  785. "__files__": metadata.get("files", []),
  786. },
  787. )
  788. if tool_servers:
  789. for tool_server in tool_servers:
  790. tool_specs = tool_server.pop("specs", [])
  791. for tool in tool_specs:
  792. tools_dict[tool["name"]] = {
  793. "spec": tool,
  794. "direct": True,
  795. "server": tool_server,
  796. }
  797. if tools_dict:
  798. if metadata.get("params", {}).get("function_calling") == "native":
  799. # If the function calling is native, then call the tools function calling handler
  800. metadata["tools"] = tools_dict
  801. form_data["tools"] = [
  802. {"type": "function", "function": tool.get("spec", {})}
  803. for tool in tools_dict.values()
  804. ]
  805. else:
  806. # If the function calling is not native, then call the tools function calling handler
  807. try:
  808. form_data, flags = await chat_completion_tools_handler(
  809. request, form_data, extra_params, user, models, tools_dict
  810. )
  811. sources.extend(flags.get("sources", []))
  812. except Exception as e:
  813. log.exception(e)
  814. try:
  815. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  816. sources.extend(flags.get("sources", []))
  817. except Exception as e:
  818. log.exception(e)
  819. # If context is not empty, insert it into the messages
  820. if len(sources) > 0:
  821. context_string = ""
  822. citation_idx_map = {}
  823. for source in sources:
  824. is_tool_result = source.get("tool_result", False)
  825. if "document" in source and not is_tool_result:
  826. for document_text, document_metadata in zip(
  827. source["document"], source["metadata"]
  828. ):
  829. source_name = source.get("source", {}).get("name", None)
  830. source_id = (
  831. document_metadata.get("source", None)
  832. or source.get("source", {}).get("id", None)
  833. or "N/A"
  834. )
  835. if source_id not in citation_idx_map:
  836. citation_idx_map[source_id] = len(citation_idx_map) + 1
  837. context_string += (
  838. f'<source id="{citation_idx_map[source_id]}"'
  839. + (f' name="{source_name}"' if source_name else "")
  840. + f">{document_text}</source>\n"
  841. )
  842. context_string = context_string.strip()
  843. prompt = get_last_user_message(form_data["messages"])
  844. if prompt is None:
  845. raise Exception("No user message found")
  846. if context_string != "":
  847. # Workaround for Ollama 2.0+ system prompt issue
  848. # TODO: replace with add_or_update_system_message
  849. if model.get("owned_by") == "ollama":
  850. form_data["messages"] = prepend_to_first_user_message_content(
  851. rag_template(
  852. request.app.state.config.RAG_TEMPLATE,
  853. context_string,
  854. prompt,
  855. ),
  856. form_data["messages"],
  857. )
  858. else:
  859. form_data["messages"] = add_or_update_system_message(
  860. rag_template(
  861. request.app.state.config.RAG_TEMPLATE,
  862. context_string,
  863. prompt,
  864. ),
  865. form_data["messages"],
  866. )
  867. # If there are citations, add them to the data_items
  868. sources = [
  869. source
  870. for source in sources
  871. if source.get("source", {}).get("name", "")
  872. or source.get("source", {}).get("id", "")
  873. ]
  874. if len(sources) > 0:
  875. events.append({"sources": sources})
  876. if model_knowledge:
  877. await event_emitter(
  878. {
  879. "type": "status",
  880. "data": {
  881. "action": "knowledge_search",
  882. "query": user_message,
  883. "done": True,
  884. "hidden": True,
  885. },
  886. }
  887. )
  888. return form_data, metadata, events
  889. async def process_chat_response(
  890. request, response, form_data, user, metadata, model, events, tasks
  891. ):
  892. async def background_tasks_handler():
  893. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  894. message = message_map.get(metadata["message_id"]) if message_map else None
  895. if message:
  896. message_list = get_message_list(message_map, metadata["message_id"])
  897. # Remove details tags and files from the messages.
  898. # as get_message_list creates a new list, it does not affect
  899. # the original messages outside of this handler
  900. messages = []
  901. for message in message_list:
  902. content = message.get("content", "")
  903. if isinstance(content, list):
  904. for item in content:
  905. if item.get("type") == "text":
  906. content = item["text"]
  907. break
  908. if isinstance(content, str):
  909. content = re.sub(
  910. r"<details\b[^>]*>.*?<\/details>|!\[.*?\]\(.*?\)",
  911. "",
  912. content,
  913. flags=re.S | re.I,
  914. ).strip()
  915. messages.append(
  916. {
  917. **message,
  918. "role": message.get(
  919. "role", "assistant"
  920. ), # Safe fallback for missing role
  921. "content": content,
  922. }
  923. )
  924. if tasks and messages:
  925. if (
  926. TASKS.FOLLOW_UP_GENERATION in tasks
  927. and tasks[TASKS.FOLLOW_UP_GENERATION]
  928. ):
  929. res = await generate_follow_ups(
  930. request,
  931. {
  932. "model": message["model"],
  933. "messages": messages,
  934. "message_id": metadata["message_id"],
  935. "chat_id": metadata["chat_id"],
  936. },
  937. user,
  938. )
  939. if res and isinstance(res, dict):
  940. if len(res.get("choices", [])) == 1:
  941. follow_ups_string = (
  942. res.get("choices", [])[0]
  943. .get("message", {})
  944. .get("content", "")
  945. )
  946. else:
  947. follow_ups_string = ""
  948. follow_ups_string = follow_ups_string[
  949. follow_ups_string.find("{") : follow_ups_string.rfind("}")
  950. + 1
  951. ]
  952. try:
  953. follow_ups = json.loads(follow_ups_string).get(
  954. "follow_ups", []
  955. )
  956. Chats.upsert_message_to_chat_by_id_and_message_id(
  957. metadata["chat_id"],
  958. metadata["message_id"],
  959. {
  960. "followUps": follow_ups,
  961. },
  962. )
  963. await event_emitter(
  964. {
  965. "type": "chat:message:follow_ups",
  966. "data": {
  967. "follow_ups": follow_ups,
  968. },
  969. }
  970. )
  971. except Exception as e:
  972. pass
  973. if TASKS.TITLE_GENERATION in tasks:
  974. user_message = get_last_user_message(messages)
  975. if user_message and len(user_message) > 100:
  976. user_message = user_message[:100] + "..."
  977. if tasks[TASKS.TITLE_GENERATION]:
  978. res = await generate_title(
  979. request,
  980. {
  981. "model": message["model"],
  982. "messages": messages,
  983. "chat_id": metadata["chat_id"],
  984. },
  985. user,
  986. )
  987. if res and isinstance(res, dict):
  988. if len(res.get("choices", [])) == 1:
  989. title_string = (
  990. res.get("choices", [])[0]
  991. .get("message", {})
  992. .get(
  993. "content", message.get("content", user_message)
  994. )
  995. )
  996. else:
  997. title_string = ""
  998. title_string = title_string[
  999. title_string.find("{") : title_string.rfind("}") + 1
  1000. ]
  1001. try:
  1002. title = json.loads(title_string).get(
  1003. "title", user_message
  1004. )
  1005. except Exception as e:
  1006. title = ""
  1007. if not title:
  1008. title = messages[0].get("content", user_message)
  1009. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1010. await event_emitter(
  1011. {
  1012. "type": "chat:title",
  1013. "data": title,
  1014. }
  1015. )
  1016. elif len(messages) == 2:
  1017. title = messages[0].get("content", user_message)
  1018. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  1019. await event_emitter(
  1020. {
  1021. "type": "chat:title",
  1022. "data": message.get("content", user_message),
  1023. }
  1024. )
  1025. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  1026. res = await generate_chat_tags(
  1027. request,
  1028. {
  1029. "model": message["model"],
  1030. "messages": messages,
  1031. "chat_id": metadata["chat_id"],
  1032. },
  1033. user,
  1034. )
  1035. if res and isinstance(res, dict):
  1036. if len(res.get("choices", [])) == 1:
  1037. tags_string = (
  1038. res.get("choices", [])[0]
  1039. .get("message", {})
  1040. .get("content", "")
  1041. )
  1042. else:
  1043. tags_string = ""
  1044. tags_string = tags_string[
  1045. tags_string.find("{") : tags_string.rfind("}") + 1
  1046. ]
  1047. try:
  1048. tags = json.loads(tags_string).get("tags", [])
  1049. Chats.update_chat_tags_by_id(
  1050. metadata["chat_id"], tags, user
  1051. )
  1052. await event_emitter(
  1053. {
  1054. "type": "chat:tags",
  1055. "data": tags,
  1056. }
  1057. )
  1058. except Exception as e:
  1059. pass
  1060. event_emitter = None
  1061. event_caller = None
  1062. if (
  1063. "session_id" in metadata
  1064. and metadata["session_id"]
  1065. and "chat_id" in metadata
  1066. and metadata["chat_id"]
  1067. and "message_id" in metadata
  1068. and metadata["message_id"]
  1069. ):
  1070. event_emitter = get_event_emitter(metadata)
  1071. event_caller = get_event_call(metadata)
  1072. # Non-streaming response
  1073. if not isinstance(response, StreamingResponse):
  1074. if event_emitter:
  1075. if isinstance(response, dict) or isinstance(response, JSONResponse):
  1076. if isinstance(response, JSONResponse) and isinstance(
  1077. response.body, bytes
  1078. ):
  1079. try:
  1080. response_data = json.loads(response.body.decode("utf-8"))
  1081. except json.JSONDecodeError:
  1082. response_data = {"error": {"detail": "Invalid JSON response"}}
  1083. else:
  1084. response_data = response
  1085. if "error" in response_data:
  1086. error = response_data["error"].get("detail", response_data["error"])
  1087. Chats.upsert_message_to_chat_by_id_and_message_id(
  1088. metadata["chat_id"],
  1089. metadata["message_id"],
  1090. {
  1091. "error": {"content": error},
  1092. },
  1093. )
  1094. if "selected_model_id" in response_data:
  1095. Chats.upsert_message_to_chat_by_id_and_message_id(
  1096. metadata["chat_id"],
  1097. metadata["message_id"],
  1098. {
  1099. "selectedModelId": response_data["selected_model_id"],
  1100. },
  1101. )
  1102. choices = response_data.get("choices", [])
  1103. if choices and choices[0].get("message", {}).get("content"):
  1104. content = response_data["choices"][0]["message"]["content"]
  1105. if content:
  1106. await event_emitter(
  1107. {
  1108. "type": "chat:completion",
  1109. "data": response_data,
  1110. }
  1111. )
  1112. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1113. await event_emitter(
  1114. {
  1115. "type": "chat:completion",
  1116. "data": {
  1117. "done": True,
  1118. "content": content,
  1119. "title": title,
  1120. },
  1121. }
  1122. )
  1123. # Save message in the database
  1124. Chats.upsert_message_to_chat_by_id_and_message_id(
  1125. metadata["chat_id"],
  1126. metadata["message_id"],
  1127. {
  1128. "role": "assistant",
  1129. "content": content,
  1130. },
  1131. )
  1132. # Send a webhook notification if the user is not active
  1133. if not get_active_status_by_user_id(user.id):
  1134. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1135. if webhook_url:
  1136. await post_webhook(
  1137. request.app.state.WEBUI_NAME,
  1138. webhook_url,
  1139. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1140. {
  1141. "action": "chat",
  1142. "message": content,
  1143. "title": title,
  1144. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1145. },
  1146. )
  1147. await background_tasks_handler()
  1148. if events and isinstance(events, list):
  1149. extra_response = {}
  1150. for event in events:
  1151. if isinstance(event, dict):
  1152. extra_response.update(event)
  1153. else:
  1154. extra_response[event] = True
  1155. response_data = {
  1156. **extra_response,
  1157. **response_data,
  1158. }
  1159. if isinstance(response, dict):
  1160. response = response_data
  1161. if isinstance(response, JSONResponse):
  1162. response = JSONResponse(
  1163. content=response_data,
  1164. headers=response.headers,
  1165. status_code=response.status_code,
  1166. )
  1167. return response
  1168. else:
  1169. if events and isinstance(events, list) and isinstance(response, dict):
  1170. extra_response = {}
  1171. for event in events:
  1172. if isinstance(event, dict):
  1173. extra_response.update(event)
  1174. else:
  1175. extra_response[event] = True
  1176. response = {
  1177. **extra_response,
  1178. **response,
  1179. }
  1180. return response
  1181. # Non standard response
  1182. if not any(
  1183. content_type in response.headers["Content-Type"]
  1184. for content_type in ["text/event-stream", "application/x-ndjson"]
  1185. ):
  1186. return response
  1187. extra_params = {
  1188. "__event_emitter__": event_emitter,
  1189. "__event_call__": event_caller,
  1190. "__user__": user.model_dump() if isinstance(user, UserModel) else {},
  1191. "__metadata__": metadata,
  1192. "__request__": request,
  1193. "__model__": model,
  1194. }
  1195. filter_functions = [
  1196. Functions.get_function_by_id(filter_id)
  1197. for filter_id in get_sorted_filter_ids(
  1198. request, model, metadata.get("filter_ids", [])
  1199. )
  1200. ]
  1201. # Streaming response
  1202. if event_emitter and event_caller:
  1203. task_id = str(uuid4()) # Create a unique task ID.
  1204. model_id = form_data.get("model", "")
  1205. def split_content_and_whitespace(content):
  1206. content_stripped = content.rstrip()
  1207. original_whitespace = (
  1208. content[len(content_stripped) :]
  1209. if len(content) > len(content_stripped)
  1210. else ""
  1211. )
  1212. return content_stripped, original_whitespace
  1213. def is_opening_code_block(content):
  1214. backtick_segments = content.split("```")
  1215. # Even number of segments means the last backticks are opening a new block
  1216. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  1217. # Handle as a background task
  1218. async def response_handler(response, events):
  1219. def serialize_content_blocks(content_blocks, raw=False):
  1220. content = ""
  1221. for block in content_blocks:
  1222. if block["type"] == "text":
  1223. block_content = block["content"].strip()
  1224. if block_content:
  1225. content = f"{content}{block_content}\n"
  1226. elif block["type"] == "tool_calls":
  1227. attributes = block.get("attributes", {})
  1228. tool_calls = block.get("content", [])
  1229. results = block.get("results", [])
  1230. if content and not content.endswith("\n"):
  1231. content += "\n"
  1232. if results:
  1233. tool_calls_display_content = ""
  1234. for tool_call in tool_calls:
  1235. tool_call_id = tool_call.get("id", "")
  1236. tool_name = tool_call.get("function", {}).get(
  1237. "name", ""
  1238. )
  1239. tool_arguments = tool_call.get("function", {}).get(
  1240. "arguments", ""
  1241. )
  1242. tool_result = None
  1243. tool_result_files = None
  1244. for result in results:
  1245. if tool_call_id == result.get("tool_call_id", ""):
  1246. tool_result = result.get("content", None)
  1247. tool_result_files = result.get("files", None)
  1248. break
  1249. if tool_result:
  1250. 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'
  1251. else:
  1252. 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'
  1253. if not raw:
  1254. content = f"{content}{tool_calls_display_content}"
  1255. else:
  1256. tool_calls_display_content = ""
  1257. for tool_call in tool_calls:
  1258. tool_call_id = tool_call.get("id", "")
  1259. tool_name = tool_call.get("function", {}).get(
  1260. "name", ""
  1261. )
  1262. tool_arguments = tool_call.get("function", {}).get(
  1263. "arguments", ""
  1264. )
  1265. 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'
  1266. if not raw:
  1267. content = f"{content}{tool_calls_display_content}"
  1268. elif block["type"] == "reasoning":
  1269. reasoning_display_content = "\n".join(
  1270. (f"> {line}" if not line.startswith(">") else line)
  1271. for line in block["content"].splitlines()
  1272. )
  1273. reasoning_duration = block.get("duration", None)
  1274. start_tag = block.get("start_tag", "")
  1275. end_tag = block.get("end_tag", "")
  1276. if content and not content.endswith("\n"):
  1277. content += "\n"
  1278. if reasoning_duration is not None:
  1279. if raw:
  1280. content = (
  1281. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1282. )
  1283. else:
  1284. 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'
  1285. else:
  1286. if raw:
  1287. content = (
  1288. f'{content}{start_tag}{block["content"]}{end_tag}\n'
  1289. )
  1290. else:
  1291. content = f'{content}<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  1292. elif block["type"] == "code_interpreter":
  1293. attributes = block.get("attributes", {})
  1294. output = block.get("output", None)
  1295. lang = attributes.get("lang", "")
  1296. content_stripped, original_whitespace = (
  1297. split_content_and_whitespace(content)
  1298. )
  1299. if is_opening_code_block(content_stripped):
  1300. # Remove trailing backticks that would open a new block
  1301. content = (
  1302. content_stripped.rstrip("`").rstrip()
  1303. + original_whitespace
  1304. )
  1305. else:
  1306. # Keep content as is - either closing backticks or no backticks
  1307. content = content_stripped + original_whitespace
  1308. if content and not content.endswith("\n"):
  1309. content += "\n"
  1310. if output:
  1311. output = html.escape(json.dumps(output))
  1312. if raw:
  1313. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  1314. else:
  1315. content = f'{content}<details type="code_interpreter" done="true" output="{output}">\n<summary>Analyzed</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1316. else:
  1317. if raw:
  1318. content = f'{content}<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  1319. else:
  1320. content = f'{content}<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  1321. else:
  1322. block_content = str(block["content"]).strip()
  1323. if block_content:
  1324. content = f"{content}{block['type']}: {block_content}\n"
  1325. return content.strip()
  1326. def convert_content_blocks_to_messages(content_blocks, raw=False):
  1327. messages = []
  1328. temp_blocks = []
  1329. for idx, block in enumerate(content_blocks):
  1330. if block["type"] == "tool_calls":
  1331. messages.append(
  1332. {
  1333. "role": "assistant",
  1334. "content": serialize_content_blocks(temp_blocks, raw),
  1335. "tool_calls": block.get("content"),
  1336. }
  1337. )
  1338. results = block.get("results", [])
  1339. for result in results:
  1340. messages.append(
  1341. {
  1342. "role": "tool",
  1343. "tool_call_id": result["tool_call_id"],
  1344. "content": result["content"],
  1345. }
  1346. )
  1347. temp_blocks = []
  1348. else:
  1349. temp_blocks.append(block)
  1350. if temp_blocks:
  1351. content = serialize_content_blocks(temp_blocks, raw)
  1352. if content:
  1353. messages.append(
  1354. {
  1355. "role": "assistant",
  1356. "content": content,
  1357. }
  1358. )
  1359. return messages
  1360. def tag_content_handler(content_type, tags, content, content_blocks):
  1361. end_flag = False
  1362. def extract_attributes(tag_content):
  1363. """Extract attributes from a tag if they exist."""
  1364. attributes = {}
  1365. if not tag_content: # Ensure tag_content is not None
  1366. return attributes
  1367. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1368. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1369. for key, value in matches:
  1370. attributes[key] = value
  1371. return attributes
  1372. if content_blocks[-1]["type"] == "text":
  1373. for start_tag, end_tag in tags:
  1374. start_tag_pattern = rf"{re.escape(start_tag)}"
  1375. if start_tag.startswith("<") and start_tag.endswith(">"):
  1376. # Match start tag e.g., <tag> or <tag attr="value">
  1377. # remove both '<' and '>' from start_tag
  1378. # Match start tag with attributes
  1379. start_tag_pattern = (
  1380. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1381. )
  1382. match = re.search(start_tag_pattern, content)
  1383. if match:
  1384. try:
  1385. attr_content = (
  1386. match.group(1) if match.group(1) else ""
  1387. ) # Ensure it's not None
  1388. except:
  1389. attr_content = ""
  1390. attributes = extract_attributes(
  1391. attr_content
  1392. ) # Extract attributes safely
  1393. # Capture everything before and after the matched tag
  1394. before_tag = content[
  1395. : match.start()
  1396. ] # Content before opening tag
  1397. after_tag = content[
  1398. match.end() :
  1399. ] # Content after opening tag
  1400. # Remove the start tag and after from the currently handling text block
  1401. content_blocks[-1]["content"] = content_blocks[-1][
  1402. "content"
  1403. ].replace(match.group(0) + after_tag, "")
  1404. if before_tag:
  1405. content_blocks[-1]["content"] = before_tag
  1406. if not content_blocks[-1]["content"]:
  1407. content_blocks.pop()
  1408. # Append the new block
  1409. content_blocks.append(
  1410. {
  1411. "type": content_type,
  1412. "start_tag": start_tag,
  1413. "end_tag": end_tag,
  1414. "attributes": attributes,
  1415. "content": "",
  1416. "started_at": time.time(),
  1417. }
  1418. )
  1419. if after_tag:
  1420. content_blocks[-1]["content"] = after_tag
  1421. tag_content_handler(
  1422. content_type, tags, after_tag, content_blocks
  1423. )
  1424. break
  1425. elif content_blocks[-1]["type"] == content_type:
  1426. start_tag = content_blocks[-1]["start_tag"]
  1427. end_tag = content_blocks[-1]["end_tag"]
  1428. if end_tag.startswith("<") and end_tag.endswith(">"):
  1429. # Match end tag e.g., </tag>
  1430. end_tag_pattern = rf"{re.escape(end_tag)}"
  1431. else:
  1432. # Handle cases where end_tag is just a tag name
  1433. end_tag_pattern = rf"{re.escape(end_tag)}"
  1434. # Check if the content has the end tag
  1435. if re.search(end_tag_pattern, content):
  1436. end_flag = True
  1437. block_content = content_blocks[-1]["content"]
  1438. # Strip start and end tags from the content
  1439. start_tag_pattern = rf"<{re.escape(start_tag)}(.*?)>"
  1440. block_content = re.sub(
  1441. start_tag_pattern, "", block_content
  1442. ).strip()
  1443. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1444. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1445. # Content inside the tag
  1446. block_content = (
  1447. split_content[0].strip() if split_content else ""
  1448. )
  1449. # Leftover content (everything after `</tag>`)
  1450. leftover_content = (
  1451. split_content[1].strip() if len(split_content) > 1 else ""
  1452. )
  1453. if block_content:
  1454. content_blocks[-1]["content"] = block_content
  1455. content_blocks[-1]["ended_at"] = time.time()
  1456. content_blocks[-1]["duration"] = int(
  1457. content_blocks[-1]["ended_at"]
  1458. - content_blocks[-1]["started_at"]
  1459. )
  1460. # Reset the content_blocks by appending a new text block
  1461. if content_type != "code_interpreter":
  1462. if leftover_content:
  1463. content_blocks.append(
  1464. {
  1465. "type": "text",
  1466. "content": leftover_content,
  1467. }
  1468. )
  1469. else:
  1470. content_blocks.append(
  1471. {
  1472. "type": "text",
  1473. "content": "",
  1474. }
  1475. )
  1476. else:
  1477. # Remove the block if content is empty
  1478. content_blocks.pop()
  1479. if leftover_content:
  1480. content_blocks.append(
  1481. {
  1482. "type": "text",
  1483. "content": leftover_content,
  1484. }
  1485. )
  1486. else:
  1487. content_blocks.append(
  1488. {
  1489. "type": "text",
  1490. "content": "",
  1491. }
  1492. )
  1493. # Clean processed content
  1494. start_tag_pattern = rf"{re.escape(start_tag)}"
  1495. if start_tag.startswith("<") and start_tag.endswith(">"):
  1496. # Match start tag e.g., <tag> or <tag attr="value">
  1497. # remove both '<' and '>' from start_tag
  1498. # Match start tag with attributes
  1499. start_tag_pattern = (
  1500. rf"<{re.escape(start_tag[1:-1])}(\s.*?)?>"
  1501. )
  1502. content = re.sub(
  1503. rf"{start_tag_pattern}(.|\n)*?{re.escape(end_tag)}",
  1504. "",
  1505. content,
  1506. flags=re.DOTALL,
  1507. )
  1508. return content, content_blocks, end_flag
  1509. message = Chats.get_message_by_id_and_message_id(
  1510. metadata["chat_id"], metadata["message_id"]
  1511. )
  1512. tool_calls = []
  1513. last_assistant_message = None
  1514. try:
  1515. if form_data["messages"][-1]["role"] == "assistant":
  1516. last_assistant_message = get_last_assistant_message(
  1517. form_data["messages"]
  1518. )
  1519. except Exception as e:
  1520. pass
  1521. content = (
  1522. message.get("content", "")
  1523. if message
  1524. else last_assistant_message if last_assistant_message else ""
  1525. )
  1526. content_blocks = [
  1527. {
  1528. "type": "text",
  1529. "content": content,
  1530. }
  1531. ]
  1532. # We might want to disable this by default
  1533. DETECT_REASONING = True
  1534. DETECT_SOLUTION = True
  1535. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1536. "code_interpreter", False
  1537. )
  1538. reasoning_tags = [
  1539. ("<think>", "</think>"),
  1540. ("<thinking>", "</thinking>"),
  1541. ("<reason>", "</reason>"),
  1542. ("<reasoning>", "</reasoning>"),
  1543. ("<thought>", "</thought>"),
  1544. ("<Thought>", "</Thought>"),
  1545. ("<|begin_of_thought|>", "<|end_of_thought|>"),
  1546. ("◁think▷", "◁/think▷"),
  1547. ]
  1548. code_interpreter_tags = [("<code_interpreter>", "</code_interpreter>")]
  1549. solution_tags = [("<|begin_of_solution|>", "<|end_of_solution|>")]
  1550. try:
  1551. for event in events:
  1552. await event_emitter(
  1553. {
  1554. "type": "chat:completion",
  1555. "data": event,
  1556. }
  1557. )
  1558. # Save message in the database
  1559. Chats.upsert_message_to_chat_by_id_and_message_id(
  1560. metadata["chat_id"],
  1561. metadata["message_id"],
  1562. {
  1563. **event,
  1564. },
  1565. )
  1566. async def stream_body_handler(response, form_data):
  1567. nonlocal content
  1568. nonlocal content_blocks
  1569. response_tool_calls = []
  1570. delta_count = 0
  1571. delta_chunk_size = max(
  1572. CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
  1573. int(
  1574. metadata.get("params", {}).get("stream_delta_chunk_size")
  1575. or 1
  1576. ),
  1577. )
  1578. last_delta_data = None
  1579. async def flush_pending_delta_data(threshold: int = 0):
  1580. nonlocal delta_count
  1581. nonlocal last_delta_data
  1582. if delta_count >= threshold and last_delta_data:
  1583. await event_emitter(
  1584. {
  1585. "type": "chat:completion",
  1586. "data": last_delta_data,
  1587. }
  1588. )
  1589. delta_count = 0
  1590. last_delta_data = None
  1591. async for line in response.body_iterator:
  1592. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1593. data = line
  1594. # Skip empty lines
  1595. if not data.strip():
  1596. continue
  1597. # "data:" is the prefix for each event
  1598. if not data.startswith("data:"):
  1599. continue
  1600. # Remove the prefix
  1601. data = data[len("data:") :].strip()
  1602. try:
  1603. data = json.loads(data)
  1604. data, _ = await process_filter_functions(
  1605. request=request,
  1606. filter_functions=filter_functions,
  1607. filter_type="stream",
  1608. form_data=data,
  1609. extra_params={"__body__": form_data, **extra_params},
  1610. )
  1611. if data:
  1612. if "event" in data:
  1613. await event_emitter(data.get("event", {}))
  1614. if "selected_model_id" in data:
  1615. model_id = data["selected_model_id"]
  1616. Chats.upsert_message_to_chat_by_id_and_message_id(
  1617. metadata["chat_id"],
  1618. metadata["message_id"],
  1619. {
  1620. "selectedModelId": model_id,
  1621. },
  1622. )
  1623. await event_emitter(
  1624. {
  1625. "type": "chat:completion",
  1626. "data": data,
  1627. }
  1628. )
  1629. else:
  1630. choices = data.get("choices", [])
  1631. if not choices:
  1632. error = data.get("error", {})
  1633. if error:
  1634. await event_emitter(
  1635. {
  1636. "type": "chat:completion",
  1637. "data": {
  1638. "error": error,
  1639. },
  1640. }
  1641. )
  1642. usage = data.get("usage", {})
  1643. if usage:
  1644. await event_emitter(
  1645. {
  1646. "type": "chat:completion",
  1647. "data": {
  1648. "usage": usage,
  1649. },
  1650. }
  1651. )
  1652. continue
  1653. delta = choices[0].get("delta", {})
  1654. delta_tool_calls = delta.get("tool_calls", None)
  1655. if delta_tool_calls:
  1656. for delta_tool_call in delta_tool_calls:
  1657. tool_call_index = delta_tool_call.get(
  1658. "index"
  1659. )
  1660. if tool_call_index is not None:
  1661. # Check if the tool call already exists
  1662. current_response_tool_call = None
  1663. for (
  1664. response_tool_call
  1665. ) in response_tool_calls:
  1666. if (
  1667. response_tool_call.get("index")
  1668. == tool_call_index
  1669. ):
  1670. current_response_tool_call = (
  1671. response_tool_call
  1672. )
  1673. break
  1674. if current_response_tool_call is None:
  1675. # Add the new tool call
  1676. delta_tool_call.setdefault(
  1677. "function", {}
  1678. )
  1679. delta_tool_call[
  1680. "function"
  1681. ].setdefault("name", "")
  1682. delta_tool_call[
  1683. "function"
  1684. ].setdefault("arguments", "")
  1685. response_tool_calls.append(
  1686. delta_tool_call
  1687. )
  1688. else:
  1689. # Update the existing tool call
  1690. delta_name = delta_tool_call.get(
  1691. "function", {}
  1692. ).get("name")
  1693. delta_arguments = (
  1694. delta_tool_call.get(
  1695. "function", {}
  1696. ).get("arguments")
  1697. )
  1698. if delta_name:
  1699. current_response_tool_call[
  1700. "function"
  1701. ]["name"] += delta_name
  1702. if delta_arguments:
  1703. current_response_tool_call[
  1704. "function"
  1705. ][
  1706. "arguments"
  1707. ] += delta_arguments
  1708. value = delta.get("content")
  1709. reasoning_content = (
  1710. delta.get("reasoning_content")
  1711. or delta.get("reasoning")
  1712. or delta.get("thinking")
  1713. )
  1714. if reasoning_content:
  1715. if (
  1716. not content_blocks
  1717. or content_blocks[-1]["type"] != "reasoning"
  1718. ):
  1719. reasoning_block = {
  1720. "type": "reasoning",
  1721. "start_tag": "<think>",
  1722. "end_tag": "</think>",
  1723. "attributes": {
  1724. "type": "reasoning_content"
  1725. },
  1726. "content": "",
  1727. "started_at": time.time(),
  1728. }
  1729. content_blocks.append(reasoning_block)
  1730. else:
  1731. reasoning_block = content_blocks[-1]
  1732. reasoning_block["content"] += reasoning_content
  1733. data = {
  1734. "content": serialize_content_blocks(
  1735. content_blocks
  1736. )
  1737. }
  1738. if value:
  1739. if (
  1740. content_blocks
  1741. and content_blocks[-1]["type"]
  1742. == "reasoning"
  1743. and content_blocks[-1]
  1744. .get("attributes", {})
  1745. .get("type")
  1746. == "reasoning_content"
  1747. ):
  1748. reasoning_block = content_blocks[-1]
  1749. reasoning_block["ended_at"] = time.time()
  1750. reasoning_block["duration"] = int(
  1751. reasoning_block["ended_at"]
  1752. - reasoning_block["started_at"]
  1753. )
  1754. content_blocks.append(
  1755. {
  1756. "type": "text",
  1757. "content": "",
  1758. }
  1759. )
  1760. content = f"{content}{value}"
  1761. if not content_blocks:
  1762. content_blocks.append(
  1763. {
  1764. "type": "text",
  1765. "content": "",
  1766. }
  1767. )
  1768. content_blocks[-1]["content"] = (
  1769. content_blocks[-1]["content"] + value
  1770. )
  1771. if DETECT_REASONING:
  1772. content, content_blocks, _ = (
  1773. tag_content_handler(
  1774. "reasoning",
  1775. reasoning_tags,
  1776. content,
  1777. content_blocks,
  1778. )
  1779. )
  1780. if DETECT_CODE_INTERPRETER:
  1781. content, content_blocks, end = (
  1782. tag_content_handler(
  1783. "code_interpreter",
  1784. code_interpreter_tags,
  1785. content,
  1786. content_blocks,
  1787. )
  1788. )
  1789. if end:
  1790. break
  1791. if DETECT_SOLUTION:
  1792. content, content_blocks, _ = (
  1793. tag_content_handler(
  1794. "solution",
  1795. solution_tags,
  1796. content,
  1797. content_blocks,
  1798. )
  1799. )
  1800. if ENABLE_REALTIME_CHAT_SAVE:
  1801. # Save message in the database
  1802. Chats.upsert_message_to_chat_by_id_and_message_id(
  1803. metadata["chat_id"],
  1804. metadata["message_id"],
  1805. {
  1806. "content": serialize_content_blocks(
  1807. content_blocks
  1808. ),
  1809. },
  1810. )
  1811. else:
  1812. data = {
  1813. "content": serialize_content_blocks(
  1814. content_blocks
  1815. ),
  1816. }
  1817. if delta:
  1818. delta_count += 1
  1819. last_delta_data = data
  1820. if delta_count >= delta_chunk_size:
  1821. await flush_pending_delta_data(delta_chunk_size)
  1822. else:
  1823. await event_emitter(
  1824. {
  1825. "type": "chat:completion",
  1826. "data": data,
  1827. }
  1828. )
  1829. except Exception as e:
  1830. done = "data: [DONE]" in line
  1831. if done:
  1832. pass
  1833. else:
  1834. log.debug(f"Error: {e}")
  1835. continue
  1836. await flush_pending_delta_data()
  1837. if content_blocks:
  1838. # Clean up the last text block
  1839. if content_blocks[-1]["type"] == "text":
  1840. content_blocks[-1]["content"] = content_blocks[-1][
  1841. "content"
  1842. ].strip()
  1843. if not content_blocks[-1]["content"]:
  1844. content_blocks.pop()
  1845. if not content_blocks:
  1846. content_blocks.append(
  1847. {
  1848. "type": "text",
  1849. "content": "",
  1850. }
  1851. )
  1852. if content_blocks[-1]["type"] == "reasoning":
  1853. reasoning_block = content_blocks[-1]
  1854. if reasoning_block.get("ended_at") is None:
  1855. reasoning_block["ended_at"] = time.time()
  1856. reasoning_block["duration"] = int(
  1857. reasoning_block["ended_at"]
  1858. - reasoning_block["started_at"]
  1859. )
  1860. if response_tool_calls:
  1861. tool_calls.append(response_tool_calls)
  1862. if response.background:
  1863. await response.background()
  1864. await stream_body_handler(response, form_data)
  1865. MAX_TOOL_CALL_RETRIES = 10
  1866. tool_call_retries = 0
  1867. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1868. tool_call_retries += 1
  1869. response_tool_calls = tool_calls.pop(0)
  1870. content_blocks.append(
  1871. {
  1872. "type": "tool_calls",
  1873. "content": response_tool_calls,
  1874. }
  1875. )
  1876. await event_emitter(
  1877. {
  1878. "type": "chat:completion",
  1879. "data": {
  1880. "content": serialize_content_blocks(content_blocks),
  1881. },
  1882. }
  1883. )
  1884. tools = metadata.get("tools", {})
  1885. results = []
  1886. for tool_call in response_tool_calls:
  1887. tool_call_id = tool_call.get("id", "")
  1888. tool_name = tool_call.get("function", {}).get("name", "")
  1889. tool_args = tool_call.get("function", {}).get("arguments", "{}")
  1890. tool_function_params = {}
  1891. try:
  1892. # json.loads cannot be used because some models do not produce valid JSON
  1893. tool_function_params = ast.literal_eval(tool_args)
  1894. except Exception as e:
  1895. log.debug(e)
  1896. # Fallback to JSON parsing
  1897. try:
  1898. tool_function_params = json.loads(tool_args)
  1899. except Exception as e:
  1900. log.error(
  1901. f"Error parsing tool call arguments: {tool_args}"
  1902. )
  1903. # Mutate the original tool call response params as they are passed back to the passed
  1904. # back to the LLM via the content blocks. If they are in a json block and are invalid json,
  1905. # this can cause downstream LLM integrations to fail (e.g. bedrock gateway) where response
  1906. # params are not valid json.
  1907. # Main case so far is no args = "" = invalid json.
  1908. log.debug(
  1909. f"Parsed args from {tool_args} to {tool_function_params}"
  1910. )
  1911. tool_call.setdefault("function", {})["arguments"] = json.dumps(
  1912. tool_function_params
  1913. )
  1914. tool_result = None
  1915. if tool_name in tools:
  1916. tool = tools[tool_name]
  1917. spec = tool.get("spec", {})
  1918. try:
  1919. allowed_params = (
  1920. spec.get("parameters", {})
  1921. .get("properties", {})
  1922. .keys()
  1923. )
  1924. tool_function_params = {
  1925. k: v
  1926. for k, v in tool_function_params.items()
  1927. if k in allowed_params
  1928. }
  1929. if tool.get("direct", False):
  1930. tool_result = await event_caller(
  1931. {
  1932. "type": "execute:tool",
  1933. "data": {
  1934. "id": str(uuid4()),
  1935. "name": tool_name,
  1936. "params": tool_function_params,
  1937. "server": tool.get("server", {}),
  1938. "session_id": metadata.get(
  1939. "session_id", None
  1940. ),
  1941. },
  1942. }
  1943. )
  1944. else:
  1945. tool_function = tool["callable"]
  1946. tool_result = await tool_function(
  1947. **tool_function_params
  1948. )
  1949. except Exception as e:
  1950. tool_result = str(e)
  1951. tool_result_files = []
  1952. if isinstance(tool_result, list):
  1953. for item in tool_result:
  1954. # check if string
  1955. if isinstance(item, str) and item.startswith("data:"):
  1956. tool_result_files.append(item)
  1957. tool_result.remove(item)
  1958. if isinstance(tool_result, dict) or isinstance(
  1959. tool_result, list
  1960. ):
  1961. tool_result = json.dumps(
  1962. tool_result, indent=2, ensure_ascii=False
  1963. )
  1964. results.append(
  1965. {
  1966. "tool_call_id": tool_call_id,
  1967. "content": tool_result,
  1968. **(
  1969. {"files": tool_result_files}
  1970. if tool_result_files
  1971. else {}
  1972. ),
  1973. }
  1974. )
  1975. content_blocks[-1]["results"] = results
  1976. content_blocks.append(
  1977. {
  1978. "type": "text",
  1979. "content": "",
  1980. }
  1981. )
  1982. await event_emitter(
  1983. {
  1984. "type": "chat:completion",
  1985. "data": {
  1986. "content": serialize_content_blocks(content_blocks),
  1987. },
  1988. }
  1989. )
  1990. try:
  1991. new_form_data = {
  1992. "model": model_id,
  1993. "stream": True,
  1994. "tools": form_data["tools"],
  1995. "messages": [
  1996. *form_data["messages"],
  1997. *convert_content_blocks_to_messages(
  1998. content_blocks, True
  1999. ),
  2000. ],
  2001. }
  2002. res = await generate_chat_completion(
  2003. request,
  2004. new_form_data,
  2005. user,
  2006. )
  2007. if isinstance(res, StreamingResponse):
  2008. await stream_body_handler(res, new_form_data)
  2009. else:
  2010. break
  2011. except Exception as e:
  2012. log.debug(e)
  2013. break
  2014. if DETECT_CODE_INTERPRETER:
  2015. MAX_RETRIES = 5
  2016. retries = 0
  2017. while (
  2018. content_blocks[-1]["type"] == "code_interpreter"
  2019. and retries < MAX_RETRIES
  2020. ):
  2021. await event_emitter(
  2022. {
  2023. "type": "chat:completion",
  2024. "data": {
  2025. "content": serialize_content_blocks(content_blocks),
  2026. },
  2027. }
  2028. )
  2029. retries += 1
  2030. log.debug(f"Attempt count: {retries}")
  2031. output = ""
  2032. try:
  2033. if content_blocks[-1]["attributes"].get("type") == "code":
  2034. code = content_blocks[-1]["content"]
  2035. if CODE_INTERPRETER_BLOCKED_MODULES:
  2036. blocking_code = textwrap.dedent(
  2037. f"""
  2038. import builtins
  2039. BLOCKED_MODULES = {CODE_INTERPRETER_BLOCKED_MODULES}
  2040. _real_import = builtins.__import__
  2041. def restricted_import(name, globals=None, locals=None, fromlist=(), level=0):
  2042. if name.split('.')[0] in BLOCKED_MODULES:
  2043. importer_name = globals.get('__name__') if globals else None
  2044. if importer_name == '__main__':
  2045. raise ImportError(
  2046. f"Direct import of module {{name}} is restricted."
  2047. )
  2048. return _real_import(name, globals, locals, fromlist, level)
  2049. builtins.__import__ = restricted_import
  2050. """
  2051. )
  2052. code = blocking_code + "\n" + code
  2053. if (
  2054. request.app.state.config.CODE_INTERPRETER_ENGINE
  2055. == "pyodide"
  2056. ):
  2057. output = await event_caller(
  2058. {
  2059. "type": "execute:python",
  2060. "data": {
  2061. "id": str(uuid4()),
  2062. "code": code,
  2063. "session_id": metadata.get(
  2064. "session_id", None
  2065. ),
  2066. },
  2067. }
  2068. )
  2069. elif (
  2070. request.app.state.config.CODE_INTERPRETER_ENGINE
  2071. == "jupyter"
  2072. ):
  2073. output = await execute_code_jupyter(
  2074. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  2075. code,
  2076. (
  2077. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  2078. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2079. == "token"
  2080. else None
  2081. ),
  2082. (
  2083. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  2084. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  2085. == "password"
  2086. else None
  2087. ),
  2088. request.app.state.config.CODE_INTERPRETER_JUPYTER_TIMEOUT,
  2089. )
  2090. else:
  2091. output = {
  2092. "stdout": "Code interpreter engine not configured."
  2093. }
  2094. log.debug(f"Code interpreter output: {output}")
  2095. if isinstance(output, dict):
  2096. stdout = output.get("stdout", "")
  2097. if isinstance(stdout, str):
  2098. stdoutLines = stdout.split("\n")
  2099. for idx, line in enumerate(stdoutLines):
  2100. if "data:image/png;base64" in line:
  2101. image_url = ""
  2102. # Extract base64 image data from the line
  2103. image_data, content_type = (
  2104. load_b64_image_data(line)
  2105. )
  2106. if image_data is not None:
  2107. image_url = upload_image(
  2108. request,
  2109. image_data,
  2110. content_type,
  2111. metadata,
  2112. user,
  2113. )
  2114. stdoutLines[idx] = (
  2115. f"![Output Image]({image_url})"
  2116. )
  2117. output["stdout"] = "\n".join(stdoutLines)
  2118. result = output.get("result", "")
  2119. if isinstance(result, str):
  2120. resultLines = result.split("\n")
  2121. for idx, line in enumerate(resultLines):
  2122. if "data:image/png;base64" in line:
  2123. image_url = ""
  2124. # Extract base64 image data from the line
  2125. image_data, content_type = (
  2126. load_b64_image_data(line)
  2127. )
  2128. if image_data is not None:
  2129. image_url = upload_image(
  2130. request,
  2131. image_data,
  2132. content_type,
  2133. metadata,
  2134. user,
  2135. )
  2136. resultLines[idx] = (
  2137. f"![Output Image]({image_url})"
  2138. )
  2139. output["result"] = "\n".join(resultLines)
  2140. except Exception as e:
  2141. output = str(e)
  2142. content_blocks[-1]["output"] = output
  2143. content_blocks.append(
  2144. {
  2145. "type": "text",
  2146. "content": "",
  2147. }
  2148. )
  2149. await event_emitter(
  2150. {
  2151. "type": "chat:completion",
  2152. "data": {
  2153. "content": serialize_content_blocks(content_blocks),
  2154. },
  2155. }
  2156. )
  2157. try:
  2158. new_form_data = {
  2159. "model": model_id,
  2160. "stream": True,
  2161. "messages": [
  2162. *form_data["messages"],
  2163. {
  2164. "role": "assistant",
  2165. "content": serialize_content_blocks(
  2166. content_blocks, raw=True
  2167. ),
  2168. },
  2169. ],
  2170. }
  2171. res = await generate_chat_completion(
  2172. request,
  2173. new_form_data,
  2174. user,
  2175. )
  2176. if isinstance(res, StreamingResponse):
  2177. await stream_body_handler(res, new_form_data)
  2178. else:
  2179. break
  2180. except Exception as e:
  2181. log.debug(e)
  2182. break
  2183. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  2184. data = {
  2185. "done": True,
  2186. "content": serialize_content_blocks(content_blocks),
  2187. "title": title,
  2188. }
  2189. if not ENABLE_REALTIME_CHAT_SAVE:
  2190. # Save message in the database
  2191. Chats.upsert_message_to_chat_by_id_and_message_id(
  2192. metadata["chat_id"],
  2193. metadata["message_id"],
  2194. {
  2195. "content": serialize_content_blocks(content_blocks),
  2196. },
  2197. )
  2198. # Send a webhook notification if the user is not active
  2199. if not get_active_status_by_user_id(user.id):
  2200. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  2201. if webhook_url:
  2202. await post_webhook(
  2203. request.app.state.WEBUI_NAME,
  2204. webhook_url,
  2205. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  2206. {
  2207. "action": "chat",
  2208. "message": content,
  2209. "title": title,
  2210. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  2211. },
  2212. )
  2213. await event_emitter(
  2214. {
  2215. "type": "chat:completion",
  2216. "data": data,
  2217. }
  2218. )
  2219. await background_tasks_handler()
  2220. except asyncio.CancelledError:
  2221. log.warning("Task was cancelled!")
  2222. await event_emitter({"type": "task-cancelled"})
  2223. if not ENABLE_REALTIME_CHAT_SAVE:
  2224. # Save message in the database
  2225. Chats.upsert_message_to_chat_by_id_and_message_id(
  2226. metadata["chat_id"],
  2227. metadata["message_id"],
  2228. {
  2229. "content": serialize_content_blocks(content_blocks),
  2230. },
  2231. )
  2232. if response.background is not None:
  2233. await response.background()
  2234. return await response_handler(response, events)
  2235. else:
  2236. # Fallback to the original response
  2237. async def stream_wrapper(original_generator, events):
  2238. def wrap_item(item):
  2239. return f"data: {item}\n\n"
  2240. for event in events:
  2241. event, _ = await process_filter_functions(
  2242. request=request,
  2243. filter_functions=filter_functions,
  2244. filter_type="stream",
  2245. form_data=event,
  2246. extra_params=extra_params,
  2247. )
  2248. if event:
  2249. yield wrap_item(json.dumps(event))
  2250. async for data in original_generator:
  2251. data, _ = await process_filter_functions(
  2252. request=request,
  2253. filter_functions=filter_functions,
  2254. filter_type="stream",
  2255. form_data=data,
  2256. extra_params=extra_params,
  2257. )
  2258. if data:
  2259. yield data
  2260. return StreamingResponse(
  2261. stream_wrapper(response.body_iterator, events),
  2262. headers=dict(response.headers),
  2263. background=response.background,
  2264. )