Consolidate experiment evidence and audit backup restore readiness
This commit is contained in:
1 parent
a940b90484
commit
4d39fc8d22
107 files changed
+13691
-420
No files matched your search
@@ -0,0 +1,181 @@
|
||||
"""
|
||||
title: Athena Context Display
|
||||
version: 1.2.0
|
||||
description: Displays the last request's context, separate from cumulative tool-loop usage.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def positive(value):
|
||||
if isinstance(value, bool):
|
||||
return None
|
||||
try:
|
||||
number = int(value)
|
||||
return number if number > 0 else None
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
return None
|
||||
|
||||
|
||||
def last_context(usage):
|
||||
"""OWUI merge_usage sums canonical fields but preserves last-call aliases.
|
||||
|
||||
Never use input_tokens, output_tokens, total_tokens or cached-token details:
|
||||
all four may be summed over the entire native tool loop.
|
||||
"""
|
||||
if not isinstance(usage, dict):
|
||||
return None
|
||||
if positive(usage.get('prompt_tokens')):
|
||||
prompt = positive(usage['prompt_tokens'])
|
||||
completion = positive(usage.get('completion_tokens')) or 0
|
||||
elif positive(usage.get('prompt_eval_count')):
|
||||
prompt = positive(usage['prompt_eval_count'])
|
||||
completion = positive(usage.get('eval_count')) or 0
|
||||
elif positive(usage.get('prompt_n')) or positive(usage.get('cache_n')):
|
||||
prompt = (positive(usage.get('prompt_n')) or 0) + (positive(usage.get('cache_n')) or 0)
|
||||
completion = positive(usage.get('predicted_n')) or 0
|
||||
else:
|
||||
return None
|
||||
return prompt + completion
|
||||
|
||||
|
||||
def number(value):
|
||||
return f'{value:,}'.replace(',', '.')
|
||||
|
||||
|
||||
def reported_model_seconds(event):
|
||||
"""Provider timings cover prefill + generation, not queue/network/tools."""
|
||||
if not isinstance(event, dict):
|
||||
return None
|
||||
fields = {}
|
||||
for name in ('usage', 'timings'):
|
||||
if isinstance(event.get(name), dict):
|
||||
fields.update(event[name])
|
||||
if 'prompt_ms' in fields and 'predicted_ms' in fields:
|
||||
values, scale = [fields['prompt_ms'], fields['predicted_ms']], 1000
|
||||
elif 'prompt_eval_duration' in fields and 'eval_duration' in fields:
|
||||
values, scale = [fields['prompt_eval_duration'], fields['eval_duration']], 1e9
|
||||
else:
|
||||
return None
|
||||
try:
|
||||
values = [float(value) for value in values]
|
||||
if any(not math.isfinite(value) or value < 0 for value in values):
|
||||
return None
|
||||
return sum(values) / scale
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
return None
|
||||
|
||||
|
||||
def phase_description(meter, now, show_rest=False):
|
||||
if not isinstance(meter, dict):
|
||||
return ''
|
||||
elapsed = max(0, now - meter['started'])
|
||||
description = f'⌛ Gesamt: {elapsed:.1f}s'
|
||||
rounds = meter.get('rounds') or []
|
||||
if not rounds or any(value is None for value in rounds):
|
||||
return description + ' · Modell: nicht vollständig messbar'
|
||||
model_seconds = sum(rounds)
|
||||
# Never hide overlapping/inconsistent provider timing with a fabricated 0.
|
||||
if model_seconds > elapsed + 0.05:
|
||||
return description + ' · Modell: Zeitwerte widersprüchlich'
|
||||
remaining = max(0, elapsed - model_seconds)
|
||||
description += f' · Modell: {model_seconds:.1f}s'
|
||||
if show_rest:
|
||||
description += f' · Rest ≈ {remaining:.1f}s (Tools/Warten/Verarbeitung)'
|
||||
return description
|
||||
|
||||
|
||||
class Filter:
|
||||
class Valves(BaseModel):
|
||||
priority: int = Field(default=100, description='Run after ordinary output filters.')
|
||||
show_rest: bool = Field(default=False, description='Show estimated tools/waiting/processing remainder.')
|
||||
show_compaction_threshold: bool = Field(default=False, description='Show the configured compaction threshold.')
|
||||
profile_windows: str = Field(default='{}', description='JSON: exact model ID -> configured profile context tokens. Refresh after changing Deck profile windows.')
|
||||
|
||||
def __init__(self):
|
||||
self.valves = self.Valves()
|
||||
|
||||
async def inlet(self, body: dict, __metadata__: dict = None) -> dict:
|
||||
if isinstance(__metadata__, dict) and not __metadata__.get('task'):
|
||||
__metadata__['_athena_phase_meter'] = {'started': time.monotonic(), 'rounds': []}
|
||||
return body
|
||||
|
||||
async def request(self, body: dict, __metadata__: dict = None) -> dict:
|
||||
meter = (__metadata__ or {}).get('_athena_phase_meter')
|
||||
if isinstance(meter, dict) and not (__metadata__ or {}).get('task'):
|
||||
meter['rounds'].append(None)
|
||||
return body
|
||||
|
||||
async def stream(self, event: dict, __metadata__: dict = None) -> dict:
|
||||
meter = (__metadata__ or {}).get('_athena_phase_meter')
|
||||
if isinstance(meter, dict) and meter.get('rounds'):
|
||||
seconds = reported_model_seconds(event)
|
||||
if seconds is not None:
|
||||
# Streaming counters are cumulative *within* each model call.
|
||||
# Replace its last value; do not sum every chunk.
|
||||
meter['rounds'][-1] = seconds
|
||||
return event
|
||||
|
||||
async def outlet(self, body: dict, __event_emitter__=None,
|
||||
__metadata__: dict = None, __model__: dict = None) -> dict:
|
||||
# No chat text changes, requests, credentials, tokenization or GPU work.
|
||||
if (__metadata__ or {}).get('task') or not __event_emitter__:
|
||||
return body
|
||||
try:
|
||||
model = __model__ if isinstance(__model__, dict) else {}
|
||||
info = model.get('info') or {}
|
||||
model_id = model.get('id') or body.get('model')
|
||||
if model_id in ('arena-model', 're_registry', 're-registry'):
|
||||
return body
|
||||
messages = body.get('messages') or []
|
||||
assistant = next((m for m in reversed(messages)
|
||||
if isinstance(m, dict) and m.get('role') == 'assistant'), None)
|
||||
if not assistant:
|
||||
return body
|
||||
usage = assistant.get('usage') or (assistant.get('info') or {}).get('usage')
|
||||
used = last_context(usage)
|
||||
try:
|
||||
windows = json.loads(self.valves.profile_windows)
|
||||
if not isinstance(windows, dict):
|
||||
windows = {}
|
||||
except (ValueError, TypeError):
|
||||
windows = {}
|
||||
# Provider metadata takes priority over the explicitly verified map.
|
||||
window = positive(model.get('context_window')) or positive((model.get('meta') or {}).get('n_ctx'))
|
||||
window = window or positive(windows.get(model_id)) or positive(windows.get(info.get('base_model_id')))
|
||||
threshold = positive((info.get('params') or {}).get('compact_token_threshold'))
|
||||
description = '🧠 Kontext: unbekannt (keine Tokenwerte der letzten Anfrage)'
|
||||
if used is not None:
|
||||
description = f'🧠 Kontext: {number(used)} Token'
|
||||
if window:
|
||||
percent = used / window * 100
|
||||
description = f'🧠 {number(used)} / {number(window)} Token ({percent:.1f} %)'
|
||||
else:
|
||||
description += ' · Profilfenster unbekannt'
|
||||
if threshold and self.valves.show_compaction_threshold:
|
||||
description += f' · Verdichtungsschwelle: {number(threshold)}'
|
||||
# Token Usage Display runs first and shares this request's metadata.
|
||||
# OWUI shows only the final status: preserve its metrics in that status.
|
||||
statistics = (__metadata__ or {}).get('_athena_token_usage_status')
|
||||
if isinstance(statistics, str) and statistics.strip():
|
||||
description = statistics + ' │ ' + description
|
||||
meter = (__metadata__ or {}).get('_athena_phase_meter')
|
||||
if isinstance(meter, dict) and meter.get('rounds') and meter['rounds'][-1] is None:
|
||||
# Non-streaming final call: only fill that call, never infer
|
||||
# earlier rounds from cumulative consumption metadata.
|
||||
meter['rounds'][-1] = reported_model_seconds({'usage': usage})
|
||||
phases = phase_description(meter, time.monotonic(), self.valves.show_rest)
|
||||
if phases:
|
||||
description += ' │ ' + phases
|
||||
await __event_emitter__({'type': 'status', 'data': {
|
||||
'description': description, 'done': True, 'hidden': False}})
|
||||
except Exception:
|
||||
# A broken display must never interrupt a model response.
|
||||
log.warning('Athena context display unavailable')
|
||||
return body
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Targeted, backed-up installation into an existing OpenWebUI SQLite DB.
|
||||
|
||||
Run in OpenWebUI's environment, with JSON {content, windows} on stdin.
|
||||
No server restart or authentication secrets. Also adapts the token-statistics
|
||||
filter to the shared, compact status line; both entries are backed up.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--db', required=True)
|
||||
parser.add_argument('--backup-dir', required=True)
|
||||
args = parser.parse_args()
|
||||
payload = json.load(sys.stdin)
|
||||
content = payload['content']
|
||||
compile(content, 'athena_context_display', 'exec')
|
||||
windows = payload['windows']
|
||||
assert isinstance(windows, dict) and all(isinstance(k, str) and type(v) is int and v > 0 for k, v in windows.items())
|
||||
c = sqlite3.connect(args.db)
|
||||
c.row_factory = sqlite3.Row
|
||||
c.execute('BEGIN IMMEDIATE')
|
||||
ident = 'athena_context_display'
|
||||
old = c.execute('select * from function where id=?', (ident,)).fetchone()
|
||||
statistics = c.execute("select * from function where id='token_usage_display'").fetchone()
|
||||
assert statistics, 'Token Usage Display must be installed first'
|
||||
owner = c.execute("select user_id from function where id='token_usage_display'").fetchone()
|
||||
if not owner:
|
||||
owner = c.execute("select id as user_id from user where role='admin' limit 1").fetchone()
|
||||
assert owner, 'No existing administrator found'
|
||||
backup_dir = Path(args.backup_dir)
|
||||
backup_dir.mkdir(parents=True, exist_ok=True)
|
||||
backup = backup_dir / ('context-display-before-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') + '.json')
|
||||
fd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, 'w') as f:
|
||||
json.dump({'id': ident, 'previous': dict(old) if old else None,
|
||||
'token_usage_display': dict(statistics)}, f)
|
||||
# Keep the upstream formatter and its valves. A tiny adapter exposes only its
|
||||
# finished display text to the following filter, via request-local metadata.
|
||||
stats_content = statistics['content']
|
||||
marker = " __metadata__['_athena_token_usage_status'] = v.separator.join(stats_parts)"
|
||||
anchor = ' if stats_parts and __event_emitter__:\n'
|
||||
if marker not in stats_content:
|
||||
assert stats_content.count(anchor) == 1, 'Unknown Token Usage Display version; refusing blind patch'
|
||||
stats_content = stats_content.replace(anchor,
|
||||
" # Athena Context Display: preserve metrics in the final status.\n"
|
||||
" if stats_parts and isinstance(__metadata__, dict):\n"
|
||||
+ marker + '\n\n' + anchor, 1)
|
||||
compile(stats_content, 'token_usage_display', 'exec')
|
||||
c.execute("update function set content=?,updated_at=? where id='token_usage_display'",
|
||||
(stats_content, int(time.time())))
|
||||
stats_valves = json.loads(statistics['valves'] or '{}')
|
||||
for key in ('show_input_tokens', 'show_output_tokens', 'show_total_tokens',
|
||||
'show_cumulative_tokens', 'show_generation_time', 'show_reasoning_tokens',
|
||||
'show_cached_tokens', 'show_audio_tokens', 'show_model_name',
|
||||
'show_data_source', 'show_context_window'):
|
||||
stats_valves[key] = False
|
||||
stats_valves.update(show_tokens_per_second=True, cost_mode='off')
|
||||
c.execute("update function set valves=? where id='token_usage_display'", (json.dumps(stats_valves),))
|
||||
valves = json.loads(old['valves'] or '{}') if old else {}
|
||||
valves.update(priority=100, profile_windows=json.dumps(windows, sort_keys=True),
|
||||
show_rest=False, show_compaction_threshold=False)
|
||||
now = int(time.time())
|
||||
if old:
|
||||
assert old['type'] == 'filter', 'Existing ID is not a filter'
|
||||
c.execute('update function set name=?,content=?,valves=?,is_active=1,is_global=1,updated_at=? where id=?',
|
||||
('Athena Context Display', content, json.dumps(valves), now, ident))
|
||||
else:
|
||||
c.execute('insert into function (id,user_id,name,type,content,meta,valves,is_active,is_global,updated_at,created_at) values (?,?,?,?,?,?,?,?,?,?,?)',
|
||||
(ident, owner['user_id'], 'Athena Context Display', 'filter', content,
|
||||
json.dumps({'description': 'Kontext der letzten Modellanfrage / konfiguriertes Profilfenster'}),
|
||||
json.dumps(valves), 1, 1, now, now))
|
||||
c.commit()
|
||||
r = c.execute('select content,is_active,is_global from function where id=?', (ident,)).fetchone()
|
||||
assert r['content'] == content and r['is_active'] and r['is_global']
|
||||
print(json.dumps({'id': ident, 'active': True, 'global': True, 'profiles': len(windows),
|
||||
'sha256': hashlib.sha256(content.encode()).hexdigest(), 'backup': str(backup)}))
|
||||
@@ -0,0 +1,114 @@
|
||||
import asyncio
|
||||
import copy
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
spec = importlib.util.spec_from_file_location('context_filter', Path(__file__).with_name('filter.py'))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
class ContextTests(unittest.TestCase):
|
||||
def test_phase_meter_prefill_and_thinking_generation_included(self):
|
||||
self.assertEqual(module.reported_model_seconds({'timings': {'prompt_ms': 500, 'predicted_ms': 1900}}), 2.4)
|
||||
self.assertEqual(module.reported_model_seconds({'usage': {'prompt_eval_duration': 500000000, 'eval_duration': 1900000000}}), 2.4)
|
||||
|
||||
def test_phase_meter_missing_and_inconsistent_timings_are_explicit(self):
|
||||
self.assertIn('nicht vollständig', module.phase_description({'started': 0, 'rounds': [1, None]}, 10))
|
||||
self.assertIn('widersprüchlich', module.phase_description({'started': 0, 'rounds': [20]}, 10))
|
||||
self.assertIsNone(module.reported_model_seconds({'timings': {'prompt_ms': float('nan'), 'predicted_ms': 1}}))
|
||||
|
||||
def test_all_model_rounds_count_once_and_requests_are_unchanged(self):
|
||||
async def run():
|
||||
f = module.Filter()
|
||||
body = {'messages': []}
|
||||
metadata = {}
|
||||
self.assertIs(await f.inlet(body, metadata), body)
|
||||
self.assertIs(await f.request(body, metadata), body)
|
||||
event = {'timings': {'prompt_ms': 500, 'predicted_ms': 1000}}
|
||||
self.assertIs(await f.stream(event, metadata), event)
|
||||
await f.stream({'timings': {'prompt_ms': 500, 'predicted_ms': 1900}}, metadata)
|
||||
await f.request(body, metadata)
|
||||
await f.stream({'timings': {'prompt_ms': 100, 'predicted_ms': 900}}, metadata)
|
||||
self.assertEqual(metadata['_athena_phase_meter']['rounds'], [2.4, 1.0])
|
||||
metadata['_athena_phase_meter']['started'] = 0
|
||||
description = module.phase_description(metadata['_athena_phase_meter'], 10, show_rest=True)
|
||||
self.assertIn('Modell: 3.4s', description)
|
||||
self.assertIn('Rest ≈ 6.6s', description)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_compact_times_hide_remainder(self):
|
||||
description = module.phase_description({'started': 0, 'rounds': [3.4]}, 10)
|
||||
self.assertEqual(description, '⌛ Gesamt: 10.0s · Modell: 3.4s')
|
||||
|
||||
def test_tool_loop_uses_last_request_not_sum_or_accumulated_cache(self):
|
||||
usage = {'input_tokens': 63001, 'output_tokens': 410, 'total_tokens': 63411,
|
||||
'prompt_tokens': 21181, 'completion_tokens': 129,
|
||||
'prompt_tokens_details': {'cached_tokens': 62410}}
|
||||
self.assertEqual(module.last_context(usage), 21310)
|
||||
|
||||
def test_llama_cache_included_once(self):
|
||||
self.assertEqual(module.last_context({'prompt_n': 198, 'cache_n': 20983, 'predicted_n': 129}), 21310)
|
||||
|
||||
def test_canonical_only_is_unknown_not_falsely_cumulative(self):
|
||||
self.assertIsNone(module.last_context({'input_tokens': 63001, 'output_tokens': 410}))
|
||||
|
||||
def test_ollama(self):
|
||||
self.assertEqual(module.last_context({'prompt_eval_count': 300, 'eval_count': 20}), 320)
|
||||
|
||||
def test_concurrent_responses_and_no_content_mutation(self):
|
||||
async def run():
|
||||
f = module.Filter()
|
||||
f.valves.profile_windows = '{"medium":160000,"fast":76800}'
|
||||
async def call(model_id, prompt):
|
||||
events = []
|
||||
async def emit(event):
|
||||
events.append(event)
|
||||
body = {'model': model_id, 'messages': [{'role': 'assistant', 'content': 'Hello',
|
||||
'usage': {'prompt_tokens': prompt, 'completion_tokens': 129}}]}
|
||||
original = copy.deepcopy(body)
|
||||
result = await f.outlet(body, emit, __model__={'id': model_id})
|
||||
self.assertEqual(result, original)
|
||||
return events[0]['data']['description']
|
||||
medium, fast = await asyncio.gather(call('medium', 21181), call('fast', 1000))
|
||||
self.assertIn('21.310 / 160.000', medium)
|
||||
self.assertIn('1.129 / 76.800', fast)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_background_task_emits_nothing(self):
|
||||
async def run():
|
||||
async def emit(event):
|
||||
self.fail('Background task emitted context status')
|
||||
body = {'messages': [{'role': 'assistant'}]}
|
||||
self.assertIs(await module.Filter().outlet(body, emit, {'task': 'title_generation'}), body)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_failed_emitter_does_not_break_answer(self):
|
||||
async def run():
|
||||
async def emit(event):
|
||||
raise RuntimeError('Disconnected client')
|
||||
body = {'messages': [{'role': 'assistant'}]}
|
||||
self.assertIs(await module.Filter().outlet(body, emit), body)
|
||||
asyncio.run(run())
|
||||
|
||||
def test_existing_throughput_and_duration_survive_final_status(self):
|
||||
async def run():
|
||||
events = []
|
||||
async def emit(event):
|
||||
events.append(event)
|
||||
body = {'model': 'medium', 'messages': [{'role': 'assistant',
|
||||
'usage': {'prompt_tokens': 21181, 'completion_tokens': 129}}]}
|
||||
f = module.Filter()
|
||||
f.valves.profile_windows = '{"medium":160000}'
|
||||
statistics = '⬆︎ 63,001 · ⬇︎ 410 · ⏱ 1.9s · ⚡ 67.8 t/s'
|
||||
metadata = {'_athena_token_usage_status': statistics}
|
||||
await f.outlet(body, emit, metadata, {'id': 'medium'})
|
||||
description = events[-1]['data']['description']
|
||||
self.assertTrue(description.startswith(statistics + ' │ '))
|
||||
self.assertIn('21.310 / 160.000', description)
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user