middleware.py 107 KB

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