55 lines
2.4 KiB
Python
55 lines
2.4 KiB
Python
"""
|
|
title: Athena Tool Context Guard
|
|
version: 1.0.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)
|
|
def __init__(self):
|
|
self.valves = self.Valves()
|
|
async def request(self, body: dict) -> dict:
|
|
# New copies prevent request-local trimming from touching stored outputs.
|
|
body = dict(body)
|
|
body['messages'] = [dict(m) for m in body.get('messages', [])]
|
|
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], self.valves.per_tool_chars)
|
|
excess = sum(len(t[k]) for t,k in refs) - self.valves.total_tool_chars
|
|
# 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) > self.valves.total_tool_chars and refs:
|
|
fair = max(len(MARK), self.valves.total_tool_chars//len(refs))
|
|
for target,key in refs:target[key]=shorten(target[key],fair)
|
|
return body
|