middleware.py 110 KB

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