middleware.py 106 KB

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