middleware.py 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  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
  18. from fastapi import BackgroundTasks
  19. from starlette.responses import Response, StreamingResponse
  20. from open_webui.models.chats import Chats
  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_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 image_generations, GenerateImageForm
  35. from open_webui.routers.pipelines import (
  36. process_pipeline_inlet_filter,
  37. process_pipeline_outlet_filter,
  38. )
  39. from open_webui.utils.webhook import post_webhook
  40. from open_webui.models.users import UserModel
  41. from open_webui.models.functions import Functions
  42. from open_webui.models.models import Models
  43. from open_webui.retrieval.utils import get_sources_from_files
  44. from open_webui.utils.chat import generate_chat_completion
  45. from open_webui.utils.task import (
  46. get_task_model_id,
  47. rag_template,
  48. tools_function_calling_generation_template,
  49. )
  50. from open_webui.utils.misc import (
  51. deep_update,
  52. get_message_list,
  53. add_or_update_system_message,
  54. add_or_update_user_message,
  55. get_last_user_message,
  56. get_last_assistant_message,
  57. prepend_to_first_user_message_content,
  58. )
  59. from open_webui.utils.tools import get_tools
  60. from open_webui.utils.plugin import load_function_module_by_id
  61. from open_webui.utils.filter import (
  62. get_sorted_filter_ids,
  63. process_filter_functions,
  64. )
  65. from open_webui.utils.code_interpreter import execute_code_jupyter
  66. from open_webui.tasks import create_task
  67. from open_webui.config import (
  68. CACHE_DIR,
  69. DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
  70. DEFAULT_CODE_INTERPRETER_PROMPT,
  71. )
  72. from open_webui.env import (
  73. SRC_LOG_LEVELS,
  74. GLOBAL_LOG_LEVEL,
  75. BYPASS_MODEL_ACCESS_CONTROL,
  76. ENABLE_REALTIME_CHAT_SAVE,
  77. )
  78. from open_webui.constants import TASKS
  79. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  80. log = logging.getLogger(__name__)
  81. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  82. async def chat_completion_tools_handler(
  83. request: Request, body: dict, user: UserModel, models, tools
  84. ) -> tuple[dict, dict]:
  85. async def get_content_from_response(response) -> Optional[str]:
  86. content = None
  87. if hasattr(response, "body_iterator"):
  88. async for chunk in response.body_iterator:
  89. data = json.loads(chunk.decode("utf-8"))
  90. content = data["choices"][0]["message"]["content"]
  91. # Cleanup any remaining background tasks if necessary
  92. if response.background is not None:
  93. await response.background()
  94. else:
  95. content = response["choices"][0]["message"]["content"]
  96. return content
  97. def get_tools_function_calling_payload(messages, task_model_id, content):
  98. user_message = get_last_user_message(messages)
  99. history = "\n".join(
  100. f"{message['role'].upper()}: \"\"\"{message['content']}\"\"\""
  101. for message in messages[::-1][:4]
  102. )
  103. prompt = f"History:\n{history}\nQuery: {user_message}"
  104. return {
  105. "model": task_model_id,
  106. "messages": [
  107. {"role": "system", "content": content},
  108. {"role": "user", "content": f"Query: {prompt}"},
  109. ],
  110. "stream": False,
  111. "metadata": {"task": str(TASKS.FUNCTION_CALLING)},
  112. }
  113. task_model_id = get_task_model_id(
  114. body["model"],
  115. request.app.state.config.TASK_MODEL,
  116. request.app.state.config.TASK_MODEL_EXTERNAL,
  117. models,
  118. )
  119. skip_files = False
  120. sources = []
  121. specs = [tool["spec"] for tool in tools.values()]
  122. tools_specs = json.dumps(specs)
  123. if request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE != "":
  124. template = request.app.state.config.TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  125. else:
  126. template = DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE
  127. tools_function_calling_prompt = tools_function_calling_generation_template(
  128. template, tools_specs
  129. )
  130. log.info(f"{tools_function_calling_prompt=}")
  131. payload = get_tools_function_calling_payload(
  132. body["messages"], task_model_id, tools_function_calling_prompt
  133. )
  134. try:
  135. response = await generate_chat_completion(request, form_data=payload, user=user)
  136. log.debug(f"{response=}")
  137. content = await get_content_from_response(response)
  138. log.debug(f"{content=}")
  139. if not content:
  140. return body, {}
  141. try:
  142. content = content[content.find("{") : content.rfind("}") + 1]
  143. if not content:
  144. raise Exception("No JSON object found in the response")
  145. result = json.loads(content)
  146. async def tool_call_handler(tool_call):
  147. nonlocal skip_files
  148. log.debug(f"{tool_call=}")
  149. tool_function_name = tool_call.get("name", None)
  150. if tool_function_name not in tools:
  151. return body, {}
  152. tool_function_params = tool_call.get("parameters", {})
  153. try:
  154. required_params = (
  155. tools[tool_function_name]
  156. .get("spec", {})
  157. .get("parameters", {})
  158. .get("required", [])
  159. )
  160. tool_function = tools[tool_function_name]["callable"]
  161. tool_function_params = {
  162. k: v
  163. for k, v in tool_function_params.items()
  164. if k in required_params
  165. }
  166. tool_output = await tool_function(**tool_function_params)
  167. except Exception as e:
  168. tool_output = str(e)
  169. if isinstance(tool_output, str):
  170. if tools[tool_function_name]["citation"]:
  171. sources.append(
  172. {
  173. "source": {
  174. "name": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  175. },
  176. "document": [tool_output],
  177. "metadata": [
  178. {
  179. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  180. }
  181. ],
  182. }
  183. )
  184. else:
  185. sources.append(
  186. {
  187. "source": {},
  188. "document": [tool_output],
  189. "metadata": [
  190. {
  191. "source": f"TOOL:{tools[tool_function_name]['toolkit_id']}/{tool_function_name}"
  192. }
  193. ],
  194. }
  195. )
  196. if tools[tool_function_name]["file_handler"]:
  197. skip_files = True
  198. # check if "tool_calls" in result
  199. if result.get("tool_calls"):
  200. for tool_call in result.get("tool_calls"):
  201. await tool_call_handler(tool_call)
  202. else:
  203. await tool_call_handler(result)
  204. except Exception as e:
  205. log.exception(f"Error: {e}")
  206. content = None
  207. except Exception as e:
  208. log.exception(f"Error: {e}")
  209. content = None
  210. log.debug(f"tool_contexts: {sources}")
  211. if skip_files and "files" in body.get("metadata", {}):
  212. del body["metadata"]["files"]
  213. return body, {"sources": sources}
  214. async def chat_web_search_handler(
  215. request: Request, form_data: dict, extra_params: dict, user
  216. ):
  217. event_emitter = extra_params["__event_emitter__"]
  218. await event_emitter(
  219. {
  220. "type": "status",
  221. "data": {
  222. "action": "web_search",
  223. "description": "Generating search query",
  224. "done": False,
  225. },
  226. }
  227. )
  228. messages = form_data["messages"]
  229. user_message = get_last_user_message(messages)
  230. queries = []
  231. try:
  232. res = await generate_queries(
  233. request,
  234. {
  235. "model": form_data["model"],
  236. "messages": messages,
  237. "prompt": user_message,
  238. "type": "web_search",
  239. },
  240. user,
  241. )
  242. response = res["choices"][0]["message"]["content"]
  243. try:
  244. bracket_start = response.find("{")
  245. bracket_end = response.rfind("}") + 1
  246. if bracket_start == -1 or bracket_end == -1:
  247. raise Exception("No JSON object found in the response")
  248. response = response[bracket_start:bracket_end]
  249. queries = json.loads(response)
  250. queries = queries.get("queries", [])
  251. except Exception as e:
  252. queries = [response]
  253. except Exception as e:
  254. log.exception(e)
  255. queries = [user_message]
  256. if len(queries) == 0:
  257. await event_emitter(
  258. {
  259. "type": "status",
  260. "data": {
  261. "action": "web_search",
  262. "description": "No search query generated",
  263. "done": True,
  264. },
  265. }
  266. )
  267. return form_data
  268. searchQuery = queries[0]
  269. await event_emitter(
  270. {
  271. "type": "status",
  272. "data": {
  273. "action": "web_search",
  274. "description": 'Searching "{{searchQuery}}"',
  275. "query": searchQuery,
  276. "done": False,
  277. },
  278. }
  279. )
  280. try:
  281. results = await process_web_search(
  282. request,
  283. SearchForm(
  284. **{
  285. "query": searchQuery,
  286. }
  287. ),
  288. user,
  289. )
  290. if results:
  291. await event_emitter(
  292. {
  293. "type": "status",
  294. "data": {
  295. "action": "web_search",
  296. "description": "Searched {{count}} sites",
  297. "query": searchQuery,
  298. "urls": results["filenames"],
  299. "done": True,
  300. },
  301. }
  302. )
  303. files = form_data.get("files", [])
  304. files.append(
  305. {
  306. "collection_name": results["collection_name"],
  307. "name": searchQuery,
  308. "type": "web_search_results",
  309. "urls": results["filenames"],
  310. }
  311. )
  312. form_data["files"] = files
  313. else:
  314. await event_emitter(
  315. {
  316. "type": "status",
  317. "data": {
  318. "action": "web_search",
  319. "description": "No search results found",
  320. "query": searchQuery,
  321. "done": True,
  322. "error": True,
  323. },
  324. }
  325. )
  326. except Exception as e:
  327. log.exception(e)
  328. await event_emitter(
  329. {
  330. "type": "status",
  331. "data": {
  332. "action": "web_search",
  333. "description": 'Error searching "{{searchQuery}}"',
  334. "query": searchQuery,
  335. "done": True,
  336. "error": True,
  337. },
  338. }
  339. )
  340. return form_data
  341. async def chat_image_generation_handler(
  342. request: Request, form_data: dict, extra_params: dict, user
  343. ):
  344. __event_emitter__ = extra_params["__event_emitter__"]
  345. await __event_emitter__(
  346. {
  347. "type": "status",
  348. "data": {"description": "Generating an image", "done": False},
  349. }
  350. )
  351. messages = form_data["messages"]
  352. user_message = get_last_user_message(messages)
  353. prompt = user_message
  354. negative_prompt = ""
  355. if request.app.state.config.ENABLE_IMAGE_PROMPT_GENERATION:
  356. try:
  357. res = await generate_image_prompt(
  358. request,
  359. {
  360. "model": form_data["model"],
  361. "messages": messages,
  362. },
  363. user,
  364. )
  365. response = res["choices"][0]["message"]["content"]
  366. try:
  367. bracket_start = response.find("{")
  368. bracket_end = response.rfind("}") + 1
  369. if bracket_start == -1 or bracket_end == -1:
  370. raise Exception("No JSON object found in the response")
  371. response = response[bracket_start:bracket_end]
  372. response = json.loads(response)
  373. prompt = response.get("prompt", [])
  374. except Exception as e:
  375. prompt = user_message
  376. except Exception as e:
  377. log.exception(e)
  378. prompt = user_message
  379. system_message_content = ""
  380. try:
  381. images = await image_generations(
  382. request=request,
  383. form_data=GenerateImageForm(**{"prompt": prompt}),
  384. user=user,
  385. )
  386. await __event_emitter__(
  387. {
  388. "type": "status",
  389. "data": {"description": "Generated an image", "done": True},
  390. }
  391. )
  392. for image in images:
  393. await __event_emitter__(
  394. {
  395. "type": "message",
  396. "data": {"content": f"![Generated Image]({image['url']})\n"},
  397. }
  398. )
  399. system_message_content = "<context>User is shown the generated image, tell the user that the image has been generated</context>"
  400. except Exception as e:
  401. log.exception(e)
  402. await __event_emitter__(
  403. {
  404. "type": "status",
  405. "data": {
  406. "description": f"An error occurred while generating an image",
  407. "done": True,
  408. },
  409. }
  410. )
  411. system_message_content = "<context>Unable to generate an image, tell the user that an error occurred</context>"
  412. if system_message_content:
  413. form_data["messages"] = add_or_update_system_message(
  414. system_message_content, form_data["messages"]
  415. )
  416. return form_data
  417. async def chat_completion_files_handler(
  418. request: Request, body: dict, user: UserModel
  419. ) -> tuple[dict, dict[str, list]]:
  420. sources = []
  421. if files := body.get("metadata", {}).get("files", None):
  422. try:
  423. queries_response = await generate_queries(
  424. request,
  425. {
  426. "model": body["model"],
  427. "messages": body["messages"],
  428. "type": "retrieval",
  429. },
  430. user,
  431. )
  432. queries_response = queries_response["choices"][0]["message"]["content"]
  433. try:
  434. bracket_start = queries_response.find("{")
  435. bracket_end = queries_response.rfind("}") + 1
  436. if bracket_start == -1 or bracket_end == -1:
  437. raise Exception("No JSON object found in the response")
  438. queries_response = queries_response[bracket_start:bracket_end]
  439. queries_response = json.loads(queries_response)
  440. except Exception as e:
  441. queries_response = {"queries": [queries_response]}
  442. queries = queries_response.get("queries", [])
  443. except Exception as e:
  444. queries = []
  445. if len(queries) == 0:
  446. queries = [get_last_user_message(body["messages"])]
  447. try:
  448. # Offload get_sources_from_files to a separate thread
  449. loop = asyncio.get_running_loop()
  450. with ThreadPoolExecutor() as executor:
  451. sources = await loop.run_in_executor(
  452. executor,
  453. lambda: get_sources_from_files(
  454. files=files,
  455. queries=queries,
  456. embedding_function=lambda query: request.app.state.EMBEDDING_FUNCTION(
  457. query, user=user
  458. ),
  459. k=request.app.state.config.TOP_K,
  460. reranking_function=request.app.state.rf,
  461. r=request.app.state.config.RELEVANCE_THRESHOLD,
  462. hybrid_search=request.app.state.config.ENABLE_RAG_HYBRID_SEARCH,
  463. ),
  464. )
  465. except Exception as e:
  466. log.exception(e)
  467. log.debug(f"rag_contexts:sources: {sources}")
  468. return body, {"sources": sources}
  469. def apply_params_to_form_data(form_data, model):
  470. params = form_data.pop("params", {})
  471. if model.get("ollama"):
  472. form_data["options"] = params
  473. if "format" in params:
  474. form_data["format"] = params["format"]
  475. if "keep_alive" in params:
  476. form_data["keep_alive"] = params["keep_alive"]
  477. else:
  478. if "seed" in params:
  479. form_data["seed"] = params["seed"]
  480. if "stop" in params:
  481. form_data["stop"] = params["stop"]
  482. if "temperature" in params:
  483. form_data["temperature"] = params["temperature"]
  484. if "max_tokens" in params:
  485. form_data["max_tokens"] = params["max_tokens"]
  486. if "top_p" in params:
  487. form_data["top_p"] = params["top_p"]
  488. if "frequency_penalty" in params:
  489. form_data["frequency_penalty"] = params["frequency_penalty"]
  490. if "reasoning_effort" in params:
  491. form_data["reasoning_effort"] = params["reasoning_effort"]
  492. return form_data
  493. async def process_chat_payload(request, form_data, metadata, user, model):
  494. form_data = apply_params_to_form_data(form_data, model)
  495. log.debug(f"form_data: {form_data}")
  496. event_emitter = get_event_emitter(metadata)
  497. event_call = get_event_call(metadata)
  498. extra_params = {
  499. "__event_emitter__": event_emitter,
  500. "__event_call__": event_call,
  501. "__user__": {
  502. "id": user.id,
  503. "email": user.email,
  504. "name": user.name,
  505. "role": user.role,
  506. },
  507. "__metadata__": metadata,
  508. "__request__": request,
  509. "__model__": model,
  510. }
  511. # Initialize events to store additional event to be sent to the client
  512. # Initialize contexts and citation
  513. if getattr(request.state, "direct", False) and hasattr(request.state, "model"):
  514. models = {
  515. request.state.model["id"]: request.state.model,
  516. }
  517. else:
  518. models = request.app.state.MODELS
  519. task_model_id = get_task_model_id(
  520. form_data["model"],
  521. request.app.state.config.TASK_MODEL,
  522. request.app.state.config.TASK_MODEL_EXTERNAL,
  523. models,
  524. )
  525. events = []
  526. sources = []
  527. user_message = get_last_user_message(form_data["messages"])
  528. model_knowledge = model.get("info", {}).get("meta", {}).get("knowledge", False)
  529. if model_knowledge:
  530. await event_emitter(
  531. {
  532. "type": "status",
  533. "data": {
  534. "action": "knowledge_search",
  535. "query": user_message,
  536. "done": False,
  537. },
  538. }
  539. )
  540. knowledge_files = []
  541. for item in model_knowledge:
  542. if item.get("collection_name"):
  543. knowledge_files.append(
  544. {
  545. "id": item.get("collection_name"),
  546. "name": item.get("name"),
  547. "legacy": True,
  548. }
  549. )
  550. elif item.get("collection_names"):
  551. knowledge_files.append(
  552. {
  553. "name": item.get("name"),
  554. "type": "collection",
  555. "collection_names": item.get("collection_names"),
  556. "legacy": True,
  557. }
  558. )
  559. else:
  560. knowledge_files.append(item)
  561. files = form_data.get("files", [])
  562. files.extend(knowledge_files)
  563. form_data["files"] = files
  564. variables = form_data.pop("variables", None)
  565. # Process the form_data through the pipeline
  566. try:
  567. form_data = await process_pipeline_inlet_filter(
  568. request, form_data, user, models
  569. )
  570. except Exception as e:
  571. raise e
  572. try:
  573. form_data, flags = await process_filter_functions(
  574. request=request,
  575. filter_ids=get_sorted_filter_ids(model),
  576. filter_type="inlet",
  577. form_data=form_data,
  578. extra_params=extra_params,
  579. )
  580. except Exception as e:
  581. raise Exception(f"Error: {e}")
  582. features = form_data.pop("features", None)
  583. if features:
  584. if "web_search" in features and features["web_search"]:
  585. form_data = await chat_web_search_handler(
  586. request, form_data, extra_params, user
  587. )
  588. if "image_generation" in features and features["image_generation"]:
  589. form_data = await chat_image_generation_handler(
  590. request, form_data, extra_params, user
  591. )
  592. if "code_interpreter" in features and features["code_interpreter"]:
  593. form_data["messages"] = add_or_update_user_message(
  594. (
  595. request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE
  596. if request.app.state.config.CODE_INTERPRETER_PROMPT_TEMPLATE != ""
  597. else DEFAULT_CODE_INTERPRETER_PROMPT
  598. ),
  599. form_data["messages"],
  600. )
  601. tool_ids = form_data.pop("tool_ids", None)
  602. files = form_data.pop("files", None)
  603. # Remove files duplicates
  604. if files:
  605. files = list({json.dumps(f, sort_keys=True): f for f in files}.values())
  606. metadata = {
  607. **metadata,
  608. "tool_ids": tool_ids,
  609. "files": files,
  610. }
  611. form_data["metadata"] = metadata
  612. tool_ids = metadata.get("tool_ids", None)
  613. log.debug(f"{tool_ids=}")
  614. if tool_ids:
  615. # If tool_ids field is present, then get the tools
  616. tools = get_tools(
  617. request,
  618. tool_ids,
  619. user,
  620. {
  621. **extra_params,
  622. "__model__": models[task_model_id],
  623. "__messages__": form_data["messages"],
  624. "__files__": metadata.get("files", []),
  625. },
  626. )
  627. log.info(f"{tools=}")
  628. if metadata.get("function_calling") == "native":
  629. # If the function calling is native, then call the tools function calling handler
  630. metadata["tools"] = tools
  631. form_data["tools"] = [
  632. {"type": "function", "function": tool.get("spec", {})}
  633. for tool in tools.values()
  634. ]
  635. else:
  636. # If the function calling is not native, then call the tools function calling handler
  637. try:
  638. form_data, flags = await chat_completion_tools_handler(
  639. request, form_data, user, models, tools
  640. )
  641. sources.extend(flags.get("sources", []))
  642. except Exception as e:
  643. log.exception(e)
  644. try:
  645. form_data, flags = await chat_completion_files_handler(request, form_data, user)
  646. sources.extend(flags.get("sources", []))
  647. except Exception as e:
  648. log.exception(e)
  649. # If context is not empty, insert it into the messages
  650. if len(sources) > 0:
  651. context_string = ""
  652. for source_idx, source in enumerate(sources):
  653. source_id = source.get("source", {}).get("name", "")
  654. if "document" in source:
  655. for doc_idx, doc_context in enumerate(source["document"]):
  656. context_string += f"<source><source_id>{source_idx}</source_id><source_context>{doc_context}</source_context></source>\n"
  657. context_string = context_string.strip()
  658. prompt = get_last_user_message(form_data["messages"])
  659. if prompt is None:
  660. raise Exception("No user message found")
  661. if (
  662. request.app.state.config.RELEVANCE_THRESHOLD == 0
  663. and context_string.strip() == ""
  664. ):
  665. log.debug(
  666. f"With a 0 relevancy threshold for RAG, the context cannot be empty"
  667. )
  668. # Workaround for Ollama 2.0+ system prompt issue
  669. # TODO: replace with add_or_update_system_message
  670. if model["owned_by"] == "ollama":
  671. form_data["messages"] = prepend_to_first_user_message_content(
  672. rag_template(
  673. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  674. ),
  675. form_data["messages"],
  676. )
  677. else:
  678. form_data["messages"] = add_or_update_system_message(
  679. rag_template(
  680. request.app.state.config.RAG_TEMPLATE, context_string, prompt
  681. ),
  682. form_data["messages"],
  683. )
  684. # If there are citations, add them to the data_items
  685. sources = [source for source in sources if source.get("source", {}).get("name", "")]
  686. if len(sources) > 0:
  687. events.append({"sources": sources})
  688. if model_knowledge:
  689. await event_emitter(
  690. {
  691. "type": "status",
  692. "data": {
  693. "action": "knowledge_search",
  694. "query": user_message,
  695. "done": True,
  696. "hidden": True,
  697. },
  698. }
  699. )
  700. return form_data, metadata, events
  701. async def process_chat_response(
  702. request, response, form_data, user, events, metadata, tasks
  703. ):
  704. async def background_tasks_handler():
  705. message_map = Chats.get_messages_by_chat_id(metadata["chat_id"])
  706. message = message_map.get(metadata["message_id"]) if message_map else None
  707. if message:
  708. messages = get_message_list(message_map, message.get("id"))
  709. if tasks and messages:
  710. if TASKS.TITLE_GENERATION in tasks:
  711. if tasks[TASKS.TITLE_GENERATION]:
  712. res = await generate_title(
  713. request,
  714. {
  715. "model": message["model"],
  716. "messages": messages,
  717. "chat_id": metadata["chat_id"],
  718. },
  719. user,
  720. )
  721. if res and isinstance(res, dict):
  722. if len(res.get("choices", [])) == 1:
  723. title_string = (
  724. res.get("choices", [])[0]
  725. .get("message", {})
  726. .get("content", message.get("content", "New Chat"))
  727. )
  728. else:
  729. title_string = ""
  730. title_string = title_string[
  731. title_string.find("{") : title_string.rfind("}") + 1
  732. ]
  733. try:
  734. title = json.loads(title_string).get(
  735. "title", "New Chat"
  736. )
  737. except Exception as e:
  738. title = ""
  739. if not title:
  740. title = messages[0].get("content", "New Chat")
  741. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  742. await event_emitter(
  743. {
  744. "type": "chat:title",
  745. "data": title,
  746. }
  747. )
  748. elif len(messages) == 2:
  749. title = messages[0].get("content", "New Chat")
  750. Chats.update_chat_title_by_id(metadata["chat_id"], title)
  751. await event_emitter(
  752. {
  753. "type": "chat:title",
  754. "data": message.get("content", "New Chat"),
  755. }
  756. )
  757. if TASKS.TAGS_GENERATION in tasks and tasks[TASKS.TAGS_GENERATION]:
  758. res = await generate_chat_tags(
  759. request,
  760. {
  761. "model": message["model"],
  762. "messages": messages,
  763. "chat_id": metadata["chat_id"],
  764. },
  765. user,
  766. )
  767. if res and isinstance(res, dict):
  768. if len(res.get("choices", [])) == 1:
  769. tags_string = (
  770. res.get("choices", [])[0]
  771. .get("message", {})
  772. .get("content", "")
  773. )
  774. else:
  775. tags_string = ""
  776. tags_string = tags_string[
  777. tags_string.find("{") : tags_string.rfind("}") + 1
  778. ]
  779. try:
  780. tags = json.loads(tags_string).get("tags", [])
  781. Chats.update_chat_tags_by_id(
  782. metadata["chat_id"], tags, user
  783. )
  784. await event_emitter(
  785. {
  786. "type": "chat:tags",
  787. "data": tags,
  788. }
  789. )
  790. except Exception as e:
  791. pass
  792. event_emitter = None
  793. event_caller = None
  794. if (
  795. "session_id" in metadata
  796. and metadata["session_id"]
  797. and "chat_id" in metadata
  798. and metadata["chat_id"]
  799. and "message_id" in metadata
  800. and metadata["message_id"]
  801. ):
  802. event_emitter = get_event_emitter(metadata)
  803. event_caller = get_event_call(metadata)
  804. # Non-streaming response
  805. if not isinstance(response, StreamingResponse):
  806. if event_emitter:
  807. if "selected_model_id" in response:
  808. Chats.upsert_message_to_chat_by_id_and_message_id(
  809. metadata["chat_id"],
  810. metadata["message_id"],
  811. {
  812. "selectedModelId": response["selected_model_id"],
  813. },
  814. )
  815. if response.get("choices", [])[0].get("message", {}).get("content"):
  816. content = response["choices"][0]["message"]["content"]
  817. if content:
  818. await event_emitter(
  819. {
  820. "type": "chat:completion",
  821. "data": response,
  822. }
  823. )
  824. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  825. await event_emitter(
  826. {
  827. "type": "chat:completion",
  828. "data": {
  829. "done": True,
  830. "content": content,
  831. "title": title,
  832. },
  833. }
  834. )
  835. # Save message in the database
  836. Chats.upsert_message_to_chat_by_id_and_message_id(
  837. metadata["chat_id"],
  838. metadata["message_id"],
  839. {
  840. "content": content,
  841. },
  842. )
  843. # Send a webhook notification if the user is not active
  844. if get_active_status_by_user_id(user.id) is None:
  845. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  846. if webhook_url:
  847. post_webhook(
  848. webhook_url,
  849. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  850. {
  851. "action": "chat",
  852. "message": content,
  853. "title": title,
  854. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  855. },
  856. )
  857. await background_tasks_handler()
  858. return response
  859. else:
  860. return response
  861. # Non standard response
  862. if not any(
  863. content_type in response.headers["Content-Type"]
  864. for content_type in ["text/event-stream", "application/x-ndjson"]
  865. ):
  866. return response
  867. # Streaming response
  868. if event_emitter and event_caller:
  869. task_id = str(uuid4()) # Create a unique task ID.
  870. model_id = form_data.get("model", "")
  871. Chats.upsert_message_to_chat_by_id_and_message_id(
  872. metadata["chat_id"],
  873. metadata["message_id"],
  874. {
  875. "model": model_id,
  876. },
  877. )
  878. def split_content_and_whitespace(content):
  879. content_stripped = content.rstrip()
  880. original_whitespace = (
  881. content[len(content_stripped) :]
  882. if len(content) > len(content_stripped)
  883. else ""
  884. )
  885. return content_stripped, original_whitespace
  886. def is_opening_code_block(content):
  887. backtick_segments = content.split("```")
  888. # Even number of segments means the last backticks are opening a new block
  889. return len(backtick_segments) > 1 and len(backtick_segments) % 2 == 0
  890. # Handle as a background task
  891. async def post_response_handler(response, events):
  892. def serialize_content_blocks(content_blocks, raw=False):
  893. content = ""
  894. for block in content_blocks:
  895. if block["type"] == "text":
  896. content = f"{content}{block['content'].strip()}\n"
  897. elif block["type"] == "tool_calls":
  898. attributes = block.get("attributes", {})
  899. block_content = block.get("content", [])
  900. results = block.get("results", [])
  901. if results:
  902. result_display_content = ""
  903. for result in results:
  904. tool_call_id = result.get("tool_call_id", "")
  905. tool_name = ""
  906. for tool_call in block_content:
  907. if tool_call.get("id", "") == tool_call_id:
  908. tool_name = tool_call.get("function", {}).get(
  909. "name", ""
  910. )
  911. break
  912. result_display_content = f"{result_display_content}\n> {tool_name}: {result.get('content', '')}"
  913. if not raw:
  914. content = f'{content}\n<details type="tool_calls" done="true" content="{html.escape(json.dumps(block_content))}" results="{html.escape(json.dumps(results))}">\n<summary>Tool Executed</summary>\n{result_display_content}\n</details>\n'
  915. else:
  916. tool_calls_display_content = ""
  917. for tool_call in block_content:
  918. tool_calls_display_content = f"{tool_calls_display_content}\n> Executing {tool_call.get('function', {}).get('name', '')}"
  919. if not raw:
  920. content = f'{content}\n<details type="tool_calls" done="false" content="{html.escape(json.dumps(block_content))}">\n<summary>Tool Executing...</summary>\n{tool_calls_display_content}\n</details>\n'
  921. elif block["type"] == "reasoning":
  922. reasoning_display_content = "\n".join(
  923. (f"> {line}" if not line.startswith(">") else line)
  924. for line in block["content"].splitlines()
  925. )
  926. reasoning_duration = block.get("duration", None)
  927. if reasoning_duration is not None:
  928. if raw:
  929. content = f'{content}\n<{block["tag"]}>{block["content"]}</{block["tag"]}>\n'
  930. else:
  931. 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'
  932. else:
  933. if raw:
  934. content = f'{content}\n<{block["tag"]}>{block["content"]}</{block["tag"]}>\n'
  935. else:
  936. content = f'{content}\n<details type="reasoning" done="false">\n<summary>Thinking…</summary>\n{reasoning_display_content}\n</details>\n'
  937. elif block["type"] == "code_interpreter":
  938. attributes = block.get("attributes", {})
  939. output = block.get("output", None)
  940. lang = attributes.get("lang", "")
  941. content_stripped, original_whitespace = (
  942. split_content_and_whitespace(content)
  943. )
  944. if is_opening_code_block(content_stripped):
  945. # Remove trailing backticks that would open a new block
  946. content = (
  947. content_stripped.rstrip("`").rstrip()
  948. + original_whitespace
  949. )
  950. else:
  951. # Keep content as is - either closing backticks or no backticks
  952. content = content_stripped + original_whitespace
  953. if output:
  954. output = html.escape(json.dumps(output))
  955. if raw:
  956. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n```output\n{output}\n```\n'
  957. else:
  958. 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'
  959. else:
  960. if raw:
  961. content = f'{content}\n<code_interpreter type="code" lang="{lang}">\n{block["content"]}\n</code_interpreter>\n'
  962. else:
  963. content = f'{content}\n<details type="code_interpreter" done="false">\n<summary>Analyzing...</summary>\n```{lang}\n{block["content"]}\n```\n</details>\n'
  964. else:
  965. block_content = str(block["content"]).strip()
  966. content = f"{content}{block['type']}: {block_content}\n"
  967. return content.strip()
  968. def convert_content_blocks_to_messages(content_blocks):
  969. messages = []
  970. temp_blocks = []
  971. for idx, block in enumerate(content_blocks):
  972. if block["type"] == "tool_calls":
  973. messages.append(
  974. {
  975. "role": "assistant",
  976. "content": serialize_content_blocks(temp_blocks),
  977. "tool_calls": block.get("content"),
  978. }
  979. )
  980. results = block.get("results", [])
  981. for result in results:
  982. messages.append(
  983. {
  984. "role": "tool",
  985. "tool_call_id": result["tool_call_id"],
  986. "content": result["content"],
  987. }
  988. )
  989. temp_blocks = []
  990. else:
  991. temp_blocks.append(block)
  992. if temp_blocks:
  993. content = serialize_content_blocks(temp_blocks)
  994. if content:
  995. messages.append(
  996. {
  997. "role": "assistant",
  998. "content": content,
  999. }
  1000. )
  1001. return messages
  1002. def tag_content_handler(content_type, tags, content, content_blocks):
  1003. end_flag = False
  1004. def extract_attributes(tag_content):
  1005. """Extract attributes from a tag if they exist."""
  1006. attributes = {}
  1007. if not tag_content: # Ensure tag_content is not None
  1008. return attributes
  1009. # Match attributes in the format: key="value" (ignores single quotes for simplicity)
  1010. matches = re.findall(r'(\w+)\s*=\s*"([^"]+)"', tag_content)
  1011. for key, value in matches:
  1012. attributes[key] = value
  1013. return attributes
  1014. if content_blocks[-1]["type"] == "text":
  1015. for tag in tags:
  1016. # Match start tag e.g., <tag> or <tag attr="value">
  1017. start_tag_pattern = rf"<{tag}(\s.*?)?>"
  1018. match = re.search(start_tag_pattern, content)
  1019. if match:
  1020. attr_content = (
  1021. match.group(1) if match.group(1) else ""
  1022. ) # Ensure it's not None
  1023. attributes = extract_attributes(
  1024. attr_content
  1025. ) # Extract attributes safely
  1026. # Capture everything before and after the matched tag
  1027. before_tag = content[
  1028. : match.start()
  1029. ] # Content before opening tag
  1030. after_tag = content[
  1031. match.end() :
  1032. ] # Content after opening tag
  1033. # Remove the start tag and after from the currently handling text block
  1034. content_blocks[-1]["content"] = content_blocks[-1][
  1035. "content"
  1036. ].replace(match.group(0) + after_tag, "")
  1037. if before_tag:
  1038. content_blocks[-1]["content"] = before_tag
  1039. if not content_blocks[-1]["content"]:
  1040. content_blocks.pop()
  1041. # Append the new block
  1042. content_blocks.append(
  1043. {
  1044. "type": content_type,
  1045. "tag": tag,
  1046. "attributes": attributes,
  1047. "content": "",
  1048. "started_at": time.time(),
  1049. }
  1050. )
  1051. if after_tag:
  1052. content_blocks[-1]["content"] = after_tag
  1053. break
  1054. elif content_blocks[-1]["type"] == content_type:
  1055. tag = content_blocks[-1]["tag"]
  1056. # Match end tag e.g., </tag>
  1057. end_tag_pattern = rf"</{tag}>"
  1058. # Check if the content has the end tag
  1059. if re.search(end_tag_pattern, content):
  1060. end_flag = True
  1061. block_content = content_blocks[-1]["content"]
  1062. # Strip start and end tags from the content
  1063. start_tag_pattern = rf"<{tag}(.*?)>"
  1064. block_content = re.sub(
  1065. start_tag_pattern, "", block_content
  1066. ).strip()
  1067. end_tag_regex = re.compile(end_tag_pattern, re.DOTALL)
  1068. split_content = end_tag_regex.split(block_content, maxsplit=1)
  1069. # Content inside the tag
  1070. block_content = (
  1071. split_content[0].strip() if split_content else ""
  1072. )
  1073. # Leftover content (everything after `</tag>`)
  1074. leftover_content = (
  1075. split_content[1].strip() if len(split_content) > 1 else ""
  1076. )
  1077. if block_content:
  1078. content_blocks[-1]["content"] = block_content
  1079. content_blocks[-1]["ended_at"] = time.time()
  1080. content_blocks[-1]["duration"] = int(
  1081. content_blocks[-1]["ended_at"]
  1082. - content_blocks[-1]["started_at"]
  1083. )
  1084. # Reset the content_blocks by appending a new text block
  1085. if content_type != "code_interpreter":
  1086. if leftover_content:
  1087. content_blocks.append(
  1088. {
  1089. "type": "text",
  1090. "content": leftover_content,
  1091. }
  1092. )
  1093. else:
  1094. content_blocks.append(
  1095. {
  1096. "type": "text",
  1097. "content": "",
  1098. }
  1099. )
  1100. else:
  1101. # Remove the block if content is empty
  1102. content_blocks.pop()
  1103. if leftover_content:
  1104. content_blocks.append(
  1105. {
  1106. "type": "text",
  1107. "content": leftover_content,
  1108. }
  1109. )
  1110. else:
  1111. content_blocks.append(
  1112. {
  1113. "type": "text",
  1114. "content": "",
  1115. }
  1116. )
  1117. # Clean processed content
  1118. content = re.sub(
  1119. rf"<{tag}(.*?)>(.|\n)*?</{tag}>",
  1120. "",
  1121. content,
  1122. flags=re.DOTALL,
  1123. )
  1124. return content, content_blocks, end_flag
  1125. message = Chats.get_message_by_id_and_message_id(
  1126. metadata["chat_id"], metadata["message_id"]
  1127. )
  1128. tool_calls = []
  1129. content = message.get("content", "") if message else ""
  1130. content_blocks = [
  1131. {
  1132. "type": "text",
  1133. "content": content,
  1134. }
  1135. ]
  1136. # We might want to disable this by default
  1137. DETECT_REASONING = True
  1138. DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
  1139. "code_interpreter", False
  1140. )
  1141. reasoning_tags = [
  1142. "think",
  1143. "thinking",
  1144. "reason",
  1145. "reasoning",
  1146. "thought",
  1147. "Thought",
  1148. ]
  1149. code_interpreter_tags = ["code_interpreter"]
  1150. try:
  1151. for event in events:
  1152. await event_emitter(
  1153. {
  1154. "type": "chat:completion",
  1155. "data": event,
  1156. }
  1157. )
  1158. # Save message in the database
  1159. Chats.upsert_message_to_chat_by_id_and_message_id(
  1160. metadata["chat_id"],
  1161. metadata["message_id"],
  1162. {
  1163. **event,
  1164. },
  1165. )
  1166. async def stream_body_handler(response):
  1167. nonlocal content
  1168. nonlocal content_blocks
  1169. response_tool_calls = []
  1170. async for line in response.body_iterator:
  1171. line = line.decode("utf-8") if isinstance(line, bytes) else line
  1172. data = line
  1173. # Skip empty lines
  1174. if not data.strip():
  1175. continue
  1176. # "data:" is the prefix for each event
  1177. if not data.startswith("data:"):
  1178. continue
  1179. # Remove the prefix
  1180. data = data[len("data:") :].strip()
  1181. try:
  1182. data = json.loads(data)
  1183. if "selected_model_id" in data:
  1184. model_id = data["selected_model_id"]
  1185. Chats.upsert_message_to_chat_by_id_and_message_id(
  1186. metadata["chat_id"],
  1187. metadata["message_id"],
  1188. {
  1189. "selectedModelId": model_id,
  1190. },
  1191. )
  1192. else:
  1193. choices = data.get("choices", [])
  1194. if not choices:
  1195. continue
  1196. delta = choices[0].get("delta", {})
  1197. delta_tool_calls = delta.get("tool_calls", None)
  1198. if delta_tool_calls:
  1199. for delta_tool_call in delta_tool_calls:
  1200. tool_call_index = delta_tool_call.get("index")
  1201. if tool_call_index is not None:
  1202. if (
  1203. len(response_tool_calls)
  1204. <= tool_call_index
  1205. ):
  1206. response_tool_calls.append(
  1207. delta_tool_call
  1208. )
  1209. else:
  1210. delta_name = delta_tool_call.get(
  1211. "function", {}
  1212. ).get("name")
  1213. delta_arguments = delta_tool_call.get(
  1214. "function", {}
  1215. ).get("arguments")
  1216. if delta_name:
  1217. response_tool_calls[
  1218. tool_call_index
  1219. ]["function"]["name"] += delta_name
  1220. if delta_arguments:
  1221. response_tool_calls[
  1222. tool_call_index
  1223. ]["function"][
  1224. "arguments"
  1225. ] += delta_arguments
  1226. value = delta.get("content")
  1227. if value:
  1228. content = f"{content}{value}"
  1229. if not content_blocks:
  1230. content_blocks.append(
  1231. {
  1232. "type": "text",
  1233. "content": "",
  1234. }
  1235. )
  1236. content_blocks[-1]["content"] = (
  1237. content_blocks[-1]["content"] + value
  1238. )
  1239. if DETECT_REASONING:
  1240. content, content_blocks, _ = (
  1241. tag_content_handler(
  1242. "reasoning",
  1243. reasoning_tags,
  1244. content,
  1245. content_blocks,
  1246. )
  1247. )
  1248. if DETECT_CODE_INTERPRETER:
  1249. content, content_blocks, end = (
  1250. tag_content_handler(
  1251. "code_interpreter",
  1252. code_interpreter_tags,
  1253. content,
  1254. content_blocks,
  1255. )
  1256. )
  1257. if end:
  1258. break
  1259. if ENABLE_REALTIME_CHAT_SAVE:
  1260. # Save message in the database
  1261. Chats.upsert_message_to_chat_by_id_and_message_id(
  1262. metadata["chat_id"],
  1263. metadata["message_id"],
  1264. {
  1265. "content": serialize_content_blocks(
  1266. content_blocks
  1267. ),
  1268. },
  1269. )
  1270. else:
  1271. data = {
  1272. "content": serialize_content_blocks(
  1273. content_blocks
  1274. ),
  1275. }
  1276. await event_emitter(
  1277. {
  1278. "type": "chat:completion",
  1279. "data": data,
  1280. }
  1281. )
  1282. except Exception as e:
  1283. done = "data: [DONE]" in line
  1284. if done:
  1285. pass
  1286. else:
  1287. log.debug("Error: ", e)
  1288. continue
  1289. if content_blocks:
  1290. # Clean up the last text block
  1291. if content_blocks[-1]["type"] == "text":
  1292. content_blocks[-1]["content"] = content_blocks[-1][
  1293. "content"
  1294. ].strip()
  1295. if not content_blocks[-1]["content"]:
  1296. content_blocks.pop()
  1297. if not content_blocks:
  1298. content_blocks.append(
  1299. {
  1300. "type": "text",
  1301. "content": "",
  1302. }
  1303. )
  1304. if response_tool_calls:
  1305. tool_calls.append(response_tool_calls)
  1306. if response.background:
  1307. await response.background()
  1308. await stream_body_handler(response)
  1309. MAX_TOOL_CALL_RETRIES = 5
  1310. tool_call_retries = 0
  1311. while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
  1312. tool_call_retries += 1
  1313. response_tool_calls = tool_calls.pop(0)
  1314. content_blocks.append(
  1315. {
  1316. "type": "tool_calls",
  1317. "content": response_tool_calls,
  1318. }
  1319. )
  1320. await event_emitter(
  1321. {
  1322. "type": "chat:completion",
  1323. "data": {
  1324. "content": serialize_content_blocks(content_blocks),
  1325. },
  1326. }
  1327. )
  1328. tools = metadata.get("tools", {})
  1329. results = []
  1330. for tool_call in response_tool_calls:
  1331. tool_call_id = tool_call.get("id", "")
  1332. tool_name = tool_call.get("function", {}).get("name", "")
  1333. tool_function_params = {}
  1334. try:
  1335. # json.loads cannot be used because some models do not produce valid JSON
  1336. tool_function_params = ast.literal_eval(
  1337. tool_call.get("function", {}).get("arguments", "{}")
  1338. )
  1339. except Exception as e:
  1340. log.debug(e)
  1341. tool_result = None
  1342. if tool_name in tools:
  1343. tool = tools[tool_name]
  1344. spec = tool.get("spec", {})
  1345. try:
  1346. required_params = spec.get("parameters", {}).get(
  1347. "required", []
  1348. )
  1349. tool_function = tool["callable"]
  1350. tool_function_params = {
  1351. k: v
  1352. for k, v in tool_function_params.items()
  1353. if k in required_params
  1354. }
  1355. tool_result = await tool_function(
  1356. **tool_function_params
  1357. )
  1358. except Exception as e:
  1359. tool_result = str(e)
  1360. results.append(
  1361. {
  1362. "tool_call_id": tool_call_id,
  1363. "content": tool_result,
  1364. }
  1365. )
  1366. content_blocks[-1]["results"] = results
  1367. content_blocks.append(
  1368. {
  1369. "type": "text",
  1370. "content": "",
  1371. }
  1372. )
  1373. await event_emitter(
  1374. {
  1375. "type": "chat:completion",
  1376. "data": {
  1377. "content": serialize_content_blocks(content_blocks),
  1378. },
  1379. }
  1380. )
  1381. try:
  1382. res = await generate_chat_completion(
  1383. request,
  1384. {
  1385. "model": model_id,
  1386. "stream": True,
  1387. "tools": form_data["tools"],
  1388. "messages": [
  1389. *form_data["messages"],
  1390. *convert_content_blocks_to_messages(content_blocks),
  1391. ],
  1392. },
  1393. user,
  1394. )
  1395. if isinstance(res, StreamingResponse):
  1396. await stream_body_handler(res)
  1397. else:
  1398. break
  1399. except Exception as e:
  1400. log.debug(e)
  1401. break
  1402. if DETECT_CODE_INTERPRETER:
  1403. MAX_RETRIES = 5
  1404. retries = 0
  1405. while (
  1406. content_blocks[-1]["type"] == "code_interpreter"
  1407. and retries < MAX_RETRIES
  1408. ):
  1409. await event_emitter(
  1410. {
  1411. "type": "chat:completion",
  1412. "data": {
  1413. "content": serialize_content_blocks(content_blocks),
  1414. },
  1415. }
  1416. )
  1417. retries += 1
  1418. log.debug(f"Attempt count: {retries}")
  1419. output = ""
  1420. try:
  1421. if content_blocks[-1]["attributes"].get("type") == "code":
  1422. code = content_blocks[-1]["content"]
  1423. if (
  1424. request.app.state.config.CODE_INTERPRETER_ENGINE
  1425. == "pyodide"
  1426. ):
  1427. output = await event_caller(
  1428. {
  1429. "type": "execute:python",
  1430. "data": {
  1431. "id": str(uuid4()),
  1432. "code": code,
  1433. "session_id": metadata.get(
  1434. "session_id", None
  1435. ),
  1436. },
  1437. }
  1438. )
  1439. elif (
  1440. request.app.state.config.CODE_INTERPRETER_ENGINE
  1441. == "jupyter"
  1442. ):
  1443. output = await execute_code_jupyter(
  1444. request.app.state.config.CODE_INTERPRETER_JUPYTER_URL,
  1445. code,
  1446. (
  1447. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_TOKEN
  1448. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1449. == "token"
  1450. else None
  1451. ),
  1452. (
  1453. request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD
  1454. if request.app.state.config.CODE_INTERPRETER_JUPYTER_AUTH
  1455. == "password"
  1456. else None
  1457. ),
  1458. )
  1459. else:
  1460. output = {
  1461. "stdout": "Code interpreter engine not configured."
  1462. }
  1463. log.debug(f"Code interpreter output: {output}")
  1464. if isinstance(output, dict):
  1465. stdout = output.get("stdout", "")
  1466. if isinstance(stdout, str):
  1467. stdoutLines = stdout.split("\n")
  1468. for idx, line in enumerate(stdoutLines):
  1469. if "data:image/png;base64" in line:
  1470. id = str(uuid4())
  1471. # ensure the path exists
  1472. os.makedirs(
  1473. os.path.join(CACHE_DIR, "images"),
  1474. exist_ok=True,
  1475. )
  1476. image_path = os.path.join(
  1477. CACHE_DIR,
  1478. f"images/{id}.png",
  1479. )
  1480. with open(image_path, "wb") as f:
  1481. f.write(
  1482. base64.b64decode(
  1483. line.split(",")[1]
  1484. )
  1485. )
  1486. stdoutLines[idx] = (
  1487. f"![Output Image {idx}](/cache/images/{id}.png)"
  1488. )
  1489. output["stdout"] = "\n".join(stdoutLines)
  1490. result = output.get("result", "")
  1491. if isinstance(result, str):
  1492. resultLines = result.split("\n")
  1493. for idx, line in enumerate(resultLines):
  1494. if "data:image/png;base64" in line:
  1495. id = str(uuid4())
  1496. # ensure the path exists
  1497. os.makedirs(
  1498. os.path.join(CACHE_DIR, "images"),
  1499. exist_ok=True,
  1500. )
  1501. image_path = os.path.join(
  1502. CACHE_DIR,
  1503. f"images/{id}.png",
  1504. )
  1505. with open(image_path, "wb") as f:
  1506. f.write(
  1507. base64.b64decode(
  1508. line.split(",")[1]
  1509. )
  1510. )
  1511. resultLines[idx] = (
  1512. f"![Output Image {idx}](/cache/images/{id}.png)"
  1513. )
  1514. output["result"] = "\n".join(resultLines)
  1515. except Exception as e:
  1516. output = str(e)
  1517. content_blocks[-1]["output"] = output
  1518. content_blocks.append(
  1519. {
  1520. "type": "text",
  1521. "content": "",
  1522. }
  1523. )
  1524. await event_emitter(
  1525. {
  1526. "type": "chat:completion",
  1527. "data": {
  1528. "content": serialize_content_blocks(content_blocks),
  1529. },
  1530. }
  1531. )
  1532. print(content_blocks, serialize_content_blocks(content_blocks))
  1533. try:
  1534. res = await generate_chat_completion(
  1535. request,
  1536. {
  1537. "model": model_id,
  1538. "stream": True,
  1539. "messages": [
  1540. *form_data["messages"],
  1541. {
  1542. "role": "assistant",
  1543. "content": serialize_content_blocks(
  1544. content_blocks, raw=True
  1545. ),
  1546. },
  1547. ],
  1548. },
  1549. user,
  1550. )
  1551. if isinstance(res, StreamingResponse):
  1552. await stream_body_handler(res)
  1553. else:
  1554. break
  1555. except Exception as e:
  1556. log.debug(e)
  1557. break
  1558. title = Chats.get_chat_title_by_id(metadata["chat_id"])
  1559. data = {
  1560. "done": True,
  1561. "content": serialize_content_blocks(content_blocks),
  1562. "title": title,
  1563. }
  1564. if not ENABLE_REALTIME_CHAT_SAVE:
  1565. # Save message in the database
  1566. Chats.upsert_message_to_chat_by_id_and_message_id(
  1567. metadata["chat_id"],
  1568. metadata["message_id"],
  1569. {
  1570. "content": serialize_content_blocks(content_blocks),
  1571. },
  1572. )
  1573. # Send a webhook notification if the user is not active
  1574. if get_active_status_by_user_id(user.id) is None:
  1575. webhook_url = Users.get_user_webhook_url_by_id(user.id)
  1576. if webhook_url:
  1577. post_webhook(
  1578. webhook_url,
  1579. f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
  1580. {
  1581. "action": "chat",
  1582. "message": content,
  1583. "title": title,
  1584. "url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
  1585. },
  1586. )
  1587. await event_emitter(
  1588. {
  1589. "type": "chat:completion",
  1590. "data": data,
  1591. }
  1592. )
  1593. await background_tasks_handler()
  1594. except asyncio.CancelledError:
  1595. print("Task was cancelled!")
  1596. await event_emitter({"type": "task-cancelled"})
  1597. if not ENABLE_REALTIME_CHAT_SAVE:
  1598. # Save message in the database
  1599. Chats.upsert_message_to_chat_by_id_and_message_id(
  1600. metadata["chat_id"],
  1601. metadata["message_id"],
  1602. {
  1603. "content": serialize_content_blocks(content_blocks),
  1604. },
  1605. )
  1606. if response.background is not None:
  1607. await response.background()
  1608. # background_tasks.add_task(post_response_handler, response, events)
  1609. task_id, _ = create_task(post_response_handler(response, events))
  1610. return {"status": True, "task_id": task_id}
  1611. else:
  1612. # Fallback to the original response
  1613. async def stream_wrapper(original_generator, events):
  1614. def wrap_item(item):
  1615. return f"data: {item}\n\n"
  1616. for event in events:
  1617. yield wrap_item(json.dumps(event))
  1618. async for data in original_generator:
  1619. yield data
  1620. return StreamingResponse(
  1621. stream_wrapper(response.body_iterator, events),
  1622. headers=dict(response.headers),
  1623. background=response.background,
  1624. )