middleware.py 110 KB

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