From aa19e7f86ee17f9f0fc988548ca29e5cec84f95a Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Wed, 11 Nov 2026 10:08:27 +0900 Subject: [PATCH] refac Co-Authored-By: Classic298 <27028174+Classic298@users.noreply.github.com> --- backend/open_webui/utils/agents/acp.py | 2 +- .../open_webui/utils/agents/claude_code.py | 2 +- backend/open_webui/utils/agents/codex.py | 2 +- backend/open_webui/utils/agents/output.py | 24 ++++++++++++------- backend/open_webui/utils/agents/pi.py | 2 +- 5 files changed, 20 insertions(+), 12 deletions(-) diff --git a/backend/open_webui/utils/agents/acp.py b/backend/open_webui/utils/agents/acp.py index f4dd1f3296..58fd1a9bc5 100644 --- a/backend/open_webui/utils/agents/acp.py +++ b/backend/open_webui/utils/agents/acp.py @@ -198,7 +198,7 @@ async def run(transport, output, prompt, images, options, *, auth_method=None): await client.request('session/set_model', {'sessionId': session_id, 'modelId': options['model']}) else: raise ValueError('Agent did not advertise model selection for this session') - await output.flush(force=True) + await output.flush(force=True, persist=True) if images and not capabilities.get('promptCapabilities', {}).get('image'): raise ValueError('This agent does not support image prompts') content = [] diff --git a/backend/open_webui/utils/agents/claude_code.py b/backend/open_webui/utils/agents/claude_code.py index 794be619b4..dcc18317e6 100644 --- a/backend/open_webui/utils/agents/claude_code.py +++ b/backend/open_webui/utils/agents/claude_code.py @@ -42,7 +42,7 @@ async def run(transport, output, prompt, images, options): kind = message.get('type') if kind == 'system' and message.get('subtype') == 'init': output.state['session_id'] = message['session_id'] - await output.flush(force=True) + await output.flush(force=True, persist=True) elif kind == 'control_request': request = message['request'] if request.get('subtype') != 'can_use_tool': diff --git a/backend/open_webui/utils/agents/codex.py b/backend/open_webui/utils/agents/codex.py index 5566608924..0849c29103 100644 --- a/backend/open_webui/utils/agents/codex.py +++ b/backend/open_webui/utils/agents/codex.py @@ -80,7 +80,7 @@ async def run(transport, output, prompt, images, options): result = await client.request('thread/resume' if options.get('resume') else 'thread/start', params) thread_id = result['thread']['id'] output.state['session_id'] = thread_id - await output.flush(force=True) + await output.flush(force=True, persist=True) turn_options = {} chat_params = options.get('params') or {} chat_params = {**chat_params, **(chat_params.get('custom_params') or {})} diff --git a/backend/open_webui/utils/agents/output.py b/backend/open_webui/utils/agents/output.py index cb2a7f06e2..8bef0a1e83 100644 --- a/backend/open_webui/utils/agents/output.py +++ b/backend/open_webui/utils/agents/output.py @@ -6,10 +6,15 @@ import json import time from uuid import uuid4 +from open_webui.models.chat_messages import ChatMessages from open_webui.models.chats import Chats from open_webui.socket.main import get_event_emitter +from open_webui.tasks import clear_response_stream, save_response_stream from open_webui.utils.auth import create_token +from open_webui.utils.misc import sanitize_data_for_db +from open_webui.utils.redis import get_redis_client from open_webui.utils.tool_permissions import requires_tool_approval +from redis.asyncio import Redis class Output: @@ -26,19 +31,16 @@ class Output: self.emitter = None self.last_flush = 0 self.last_save = 0 - self.save_task = None + self.redis: Redis | None = get_redis_client(async_mode=True) self.lock = asyncio.Lock() async def flush(self, done=False, force=False, persist=False): - if self.save_task and self.save_task.done(): - self.save_task.result() if not force and not done and time.monotonic() - self.last_flush < 0.05: return if persist or done: # Approval cards must exist in the DB before users can answer them. - if self.save_task: - await asyncio.shield(self.save_task) await self.save(done=done) + await clear_response_stream(self.redis, self.metadata.get('task_id')) if self.emitter is None: self.emitter = await get_event_emitter(self.metadata, update_db=False) await self.emitter( @@ -54,8 +56,13 @@ class Output: ) self.last_flush = time.monotonic() if not (persist or done) and time.monotonic() - self.last_save >= 1: - if self.save_task is None or self.save_task.done(): - self.save_task = asyncio.create_task(self.save()) + chat_id, message_id = self.metadata['chat_id'], self.metadata['message_id'] + if not await ChatMessages.get_message_by_id(f'{chat_id}-{message_id}'): + raise ValueError('Agent chat message no longer exists') + data = sanitize_data_for_db({'content': self.content, 'output': self.items}) + await save_response_stream(self.redis, self.metadata.get('task_id'), chat_id, message_id, data['output']) + await ChatMessages.upsert_message(message_id, chat_id, self.user.id, data) + self.last_save = time.monotonic() async def save(self, done=False): async with self.lock: @@ -156,6 +163,7 @@ class Output: ): resolution = {'action': 'approve'} self.items.append(item) + pending = resolution is None if resolution is None: await self.flush(force=True, persist=True) deadline = time.monotonic() + timeout if timeout is not None else None @@ -184,6 +192,6 @@ class Output: 'status': 'completed', } ) - await self.flush(force=True, persist=True) + await self.flush(force=True, persist=pending) return resolution await asyncio.sleep(0.5) diff --git a/backend/open_webui/utils/agents/pi.py b/backend/open_webui/utils/agents/pi.py index 3e468f61bc..125a6a9b32 100644 --- a/backend/open_webui/utils/agents/pi.py +++ b/backend/open_webui/utils/agents/pi.py @@ -122,7 +122,7 @@ async def run(transport, output, prompt, images, options): output.state['session_id'] = state['sessionId'] if options.get('resume') and state['sessionId'] != options['resume']: raise ValueError('Pi resumed a different conversation') - await output.flush(force=True) + await output.flush(force=True, persist=True) content = [] for image in images: prefix, data = image.split(',', 1)