middleware.py 108 KB

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