middleware.py 110 KB

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