middleware.py 100 KB

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