middleware.py 85 KB

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