1
0

middleware.py 99 KB

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