84 lines
4.5 KiB
Python
84 lines
4.5 KiB
Python
"""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)}))
|