Explain backend rejections without exposing private error payloads

This commit is contained in:
Mikei386 committed 2026-10-13 16:58:35 +02:00
1 parent 1adf94609d
commit fd16a5bc9a
3 files changed
+117 -16

No files matched your search

@@ -0,0 +1,21 @@
# Sichere Backend-Fehlermeldungen
Deck übersetzt bekannte Fehlerformate in deutsche Meldungen mit stabilen API-Codes.
Llama-Kontextfehler werden aus numerischen Feldern gelesen; Strata-Kontextfehler
werden am festen Meldungspräfix erkannt. Antwortreserve und verbleibender Platz
werden getrennt ausgewiesen. Die Laufzeit wird korrekt benannt.
Weitere Klassen: nicht unterstützte Parameterkombinationen, Vision-Encoder,
Bildplatzhalter, Denkstufen, Werkzeug-Schema, Stop-Sequenzen, GPU-Speichermangel,
Workerstart und HTTP 401/403/404/409/429/502/503/504.
Unbekannte Fehler nennen HTTP-Status und Kennung, ohne die Ursache zu behaupten.
Kein beliebiger Backend-Text, keine Anfrage, Pfade oder Zugangsdaten werden reflektiert.
Keine automatische Kürzung, Konfigurationsänderung oder Wiederholung.
Validierung: `python3 -m unittest test_upstream_diagnostics test_endpoint.UpstreamErrorTests`
(8 Tests erfolgreich, einschließlich der beobachteten 100462/32000/131072-Ablehnung).
Native Installation/Restore: Änderung liegt in endpoint.py, bereits Bestandteil
der Installer-Dateiliste. Keine neue Abhängigkeit oder Konfiguration nötig.
Native Dienste müssen nach Aktualisierung im Wartungsfenster neu gestartet werden.
Ein frischer vollständiger Restore wurde nicht getestet.
+68 -16
View File
@@ -25,23 +25,75 @@ class APIError(ValueError):
def __init__(self,message,status=400,code='invalid_request_error'):
super().__init__(message);self.status=status;self.code=code
def chat_upstream_error(status, raw):
"""Expose known, safe llama.cpp limits without reflecting request content."""
def chat_upstream_error(status, raw, runtime=None):
"""Translate verified error formats; never echo arbitrary upstream text."""
backend = {'strata': 'Strata', 'llama': 'llama.cpp'}.get(runtime, 'Modell-Backend')
detail = {}
try:
detail=json.loads(raw)
error=detail.get('error',{}) if isinstance(detail,dict) else {}
if error.get('type')=='exceed_context_size_error':
needed=error.get('n_prompt_tokens');available=error.get('n_ctx')
if all(type(value) is int and 0<value<=2097152 for value in (needed,available)):
needed_text=f'{needed:,}'.replace(',','.');available_text=f'{available:,}'.replace(',','.')
return APIError(
f'Die Anfrage benötigt {needed_text} Kontext-Tokens, das aktive Profil bietet {available_text}. '
'Kontext im Profil erhöhen oder die Anfrage verkürzen.',
400,'context_length_exceeded')
except (ValueError,TypeError,AttributeError):
value = json.loads(raw)
if isinstance(value, dict):
error = value.get('error', {})
detail = error if isinstance(error, dict) else {'message': error} if isinstance(error, str) else {}
except (ValueError, TypeError):
pass
return APIError('llama.cpp hat die Anfrage abgelehnt. Kontext und Anfrageparameter prüfen.',
status if 400<=status<600 else 502,'upstream_error')
message = detail.get('message', '')
message = message if isinstance(message, str) else ''
def number(value):
return type(value) is int and 0 <= value <= 2097152
def fmt(value):
return f'{value:,}'.replace(',', '.')
def result(text, code, http=None):
return APIError(f'{backend}: {text}', http or (status if 400 <= status < 600 else 502), code)
if detail.get('type') == 'exceed_context_size_error':
needed, available = detail.get('n_prompt_tokens'), detail.get('n_ctx')
if number(needed) and number(available) and available > 0:
return result(f'Die Anfrage benötigt {fmt(needed)} Kontext-Tokens; verfügbar sind {fmt(available)}. '
'Chat verkürzen oder ein Profil mit größerem Kontext wählen.', 'context_length_exceeded', 400)
# Strata emits a textual ValueError, unlike llama.cpp's structured fields.
match = re.match(r'request exceeds the context window: prompt \((\d+) tokens\) \+ max tokens \((\d+)\) exceeds the context \((\d+)\)', message)
if match:
prompt, output, context = map(int, match.groups())
room = re.search(r'at most (\d+) here', message)
allowed = int(room.group(1)) if room else None
if all(number(v) for v in (prompt, output, context)) and context > 0:
hint = f' Antwortlimit auf höchstens {fmt(allowed)} Tokens reduzieren.' if number(allowed) else ' Antwortlimit reduzieren oder Chat verkürzen.'
return result(f'Anfrage {fmt(prompt)} + Antwortreserve {fmt(output)} überschreiten das Kontextfenster '
f'von {fmt(context)} Tokens.' + hint, 'context_length_exceeded', 400)
match = re.match(r'request exceeds the context window: prompt \((\d+) tokens\) leaves no room to answer in the context \((\d+)\)', message)
if match and all(number(int(v)) for v in match.groups()):
prompt, context = map(int, match.groups())
return result(f'Die Anfrage belegt {fmt(prompt)} Tokens bei {fmt(context)} Kontext-Tokens; kein Platz für eine Antwort. '
'Chat verkürzen oder größeres Kontextprofil wählen.', 'context_length_exceeded', 400)
known = (
('structured response_format with tools/MCP is not supported', 'Strukturierte JSON-Ausgabe und Werkzeuge sind in dieser Kombination nicht unterstützt. response_format deaktivieren.', 'unsupported_parameter_combination'),
('a forced tool_choice with MCP tools is not supported', 'Erzwungene Werkzeugauswahl ist mit den internen MCP-Werkzeugen nicht unterstützt. tool_choice auf auto setzen.', 'unsupported_parameter_combination'),
('this server was started without the vision encoder', 'Dieser Worker wurde ohne Vision-Encoder gestartet. Vision im Profil bereitstellen oder Bilder entfernen.', 'vision_unavailable'),
('the prompt and its images do not match', 'Bildanzahl und Bildplatzhalter der Anfrage stimmen nicht überein. Bildanfrage neu erstellen.', 'image_prompt_mismatch'),
('unknown reasoning effort ', 'Die Denkstufe ist ungültig. Strata unterstützt none, low, medium und high.', 'invalid_reasoning_effort'),
('stop takes at most ', 'Zu viele Stop-Sequenzen in der Anfrage. Stop-Parameter reduzieren.', 'invalid_stop_parameter'),
('stop must be a string or a list of strings', 'stop muss Text oder eine Liste von Texten sein.', 'invalid_stop_parameter'),
('tools must be a list of tool objects', 'Das Werkzeug-Schema ist ungültig. tools muss eine Liste von Werkzeugobjekten sein.', 'invalid_tool_schema'),
('CUDA out of memory', 'GPU-Speicher reicht nicht aus. Speicherbelegung, Kontextgröße und Modellverteilung prüfen.', 'gpu_memory_exhausted'),
('the engine is starting', 'Der Modellworker startet noch. Nach dem Laden erneut versuchen.', 'worker_starting'),
)
for prefix, text, code in known:
if message.startswith(prefix):
return result(text, code)
statuses = {
401: ('Backend-Authentifizierung fehlgeschlagen. Interne Worker-Zugangsdaten prüfen.', 'upstream_authentication_failed'),
403: ('Das Backend verweigert den Zugriff. Zugriffsregeln und Berechtigungen prüfen.', 'upstream_access_denied'),
404: ('Backend-Modell oder API-Route nicht gefunden. Modellzuordnung und Endpunkt prüfen.', 'upstream_not_found'),
409: ('Backend meldet einen Konflikt; möglicherweise ist der Modellslot belegt. Laufende Anfrage abwarten.', 'upstream_conflict'),
429: ('Backend-Anfragelimit erreicht. Laufende Anfragen abwarten und später erneut versuchen.', 'upstream_rate_limit'),
502: ('Ungültige Antwort des Backends oder seines Proxys.', 'upstream_bad_gateway'),
503: ('Backend derzeit nicht verfügbar. Worker-Zustand prüfen.', 'upstream_unavailable'),
504: ('Backend hat nicht rechtzeitig geantwortet. Worker und Anfragegröße prüfen.', 'upstream_timeout'),
}
if status in statuses:
text, code = statuses[status]
return result(text + f' (HTTP {status})', code)
return result(f'Anfrage abgelehnt (HTTP {status if 400 <= status < 600 else 502}; Kennung upstream_error). '
'Der genaue Grund wurde nicht erkannt; weder Kontextüberschreitung noch Parameterfehler sind damit bewiesen.', 'upstream_error')
class Endpoint:
def __init__(self,root,profiles,worker,scheduler,images,credentials,management_port):
@@ -479,7 +531,7 @@ class APIHandler(BaseHTTPRequestHandler):
conn.request('POST','/v1/chat/completions',body=json.dumps(body).encode(),headers={'Content-Type':'application/json','Authorization':'Bearer '+key})
response=conn.getresponse()
if response.status!=200:
raise chat_upstream_error(response.status,response.read(65536))
raise chat_upstream_error(response.status,response.read(65536),ep.worker.status().get('runtime','llama'))
if not data.get('stream'):
raw=response.read(16*1024*1024+1)
if len(raw)>16*1024*1024:raise InferenceError('Modellantwort überschreitet 16 MiB.')
+28
View File
@@ -0,0 +1,28 @@
import json
import unittest
from endpoint import chat_upstream_error
class DiagnosticsTests(unittest.TestCase):
def error(self,msg,status=400):return chat_upstream_error(status,json.dumps({'error':{'message':msg}}).encode(),'strata')
def test_real_reservation_overflow(self):
e=self.error('request exceeds the context window: prompt (100462 tokens) + max tokens (32000) exceeds the context (131072); requests are never truncated. Send a smaller max_tokens (at most 30602 here), or SECRET')
self.assertEqual(e.code,'context_length_exceeded')
for value in ('Strata','100.462','32.000','131.072','30.602'):self.assertIn(value,str(e))
self.assertNotIn('SECRET',str(e))
def test_prompt_overflow(self):
e=self.error('request exceeds the context window: prompt (131100 tokens) leaves no room to answer in the context (131072); requests are never truncated')
self.assertEqual(e.code,'context_length_exceeded');self.assertIn('kein Platz',str(e))
def test_limits(self):
e=self.error('request exceeds the context window: prompt (99999999999 tokens) + max tokens (32000) exceeds the context (131072)')
self.assertEqual(e.code,'upstream_error');self.assertNotIn('99999999999',str(e))
def test_known_errors(self):
cases={'structured response_format with tools/MCP is not supported':'unsupported_parameter_combination','unknown reasoning effort SECRET':'invalid_reasoning_effort','this server was started without the vision encoder SECRET':'vision_unavailable','the prompt and its images do not match':'image_prompt_mismatch','tools must be a list of tool objects SECRET':'invalid_tool_schema','stop takes at most 4 strings SECRET':'invalid_stop_parameter','CUDA out of memory SECRET':'gpu_memory_exhausted'}
for msg,code in cases.items():
with self.subTest(code=code):
e=self.error(msg);self.assertEqual(e.code,code);self.assertNotIn('SECRET',str(e))
def test_status_and_privacy(self):
for status in (400,401,403,404,409,422,429,500,502,503,504):
with self.subTest(status=status):
e=self.error('PRIVATE PASSWORD PROMPT',status);self.assertEqual(e.status,status);self.assertIn(str(status),str(e));self.assertNotIn('PRIVATE',str(e))
for raw in (b'private non JSON',b'[]',b'{"error":null}'):
self.assertEqual(chat_upstream_error(400,raw).code,'upstream_error')
def test_no_embedded_match(self):self.assertEqual(self.error('User said: CUDA out of memory').code,'upstream_error')