Files
Athena-Deck/integrations/openwebui-tool-context-guard/filter.py
T

62 lines
2.9 KiB
Python

"""
title: Athena Tool Context Guard
version: 1.2.0
description: Bounds tool text before every native tool-loop model request; preserves stored UI output.
"""
from pydantic import BaseModel, Field
MARK = '\n[TOOL OUTPUT SHORTENED FOR CONTEXT: full result remains in the chat/tool output. Query a narrower range or selected JSON fields if needed.]\n'
def shorten(text, limit):
if len(text) <= limit:
return text
room = max(0, limit - len(MARK))
head = room * 3 // 4
return text[:head] + MARK + (text[-(room-head):] if room-head else '')
class Filter:
class Valves(BaseModel):
priority: int = Field(default=99)
per_tool_chars: int = Field(default=12000, ge=2000)
total_tool_chars: int = Field(default=60000, ge=12000)
profile_windows: dict[str, int] = Field(default_factory=dict)
def __init__(self):
self.valves = self.Valves()
async def request(self, body: dict, __model__: dict = None, __metadata__: dict = None) -> dict:
# New copies prevent request-local trimming from touching stored outputs.
body = dict(body)
body['messages'] = [dict(m) for m in body.get('messages', [])]
model = __model__ or {}
model_id = model.get('id') or body.get('model')
window = model.get('context_window') or (model.get('info') or {}).get('meta', {}).get('n_ctx') or self.valves.profile_windows.get(model_id) or 32768
if not isinstance(window, int) or window <= 0: window = 32768
total_limit = min(self.valves.total_tool_chars, max(2000, window // 2))
per_limit = min(self.valves.per_tool_chars, total_limit)
refs = []
for m in body['messages']:
if m.get('role') != 'tool':
continue
content = m.get('content')
if isinstance(content, str):
refs.append((m, 'content'))
elif isinstance(content, list):
m['content'] = [dict(p) if isinstance(p,dict) else p for p in content]
for p in m['content']:
if isinstance(p,dict) and p.get('type') in ('text','input_text') and isinstance(p.get('text'),str):
refs.append((p,'text'))
for target,key in refs:
target[key] = shorten(target[key], per_limit)
excess = sum(len(t[k]) for t,k in refs) - total_limit
# Trim oldest results first; recent evidence and errors stay most detailed.
for target,key in refs:
if excess <= 0:break
before = len(target[key])
limit = max(1000, before-excess)
target[key] = shorten(target[key],limit)
excess -= before-len(target[key])
# With many hundreds of results, preserve every tool ID but reduce text.
if sum(len(t[k]) for t,k in refs) > total_limit and refs:
fair = max(len(MARK), total_limit//len(refs))
for target,key in refs:target[key]=shorten(target[key],fair)
return body