1
0

middleware.py 107 KB

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