middleware.py 98 KB

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