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
|
||||
Reference in new issue
Block a user