middleware.py 108 KB

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