middleware.py 106 KB

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