middleware.py 99 KB

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