Files
Athena-Deck/chat_test.py
T

148 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Ephemeral admin chat tests using the same worker and leases as the API."""
import json
import math
import socket
import threading
import time
import uuid
from typing import Any
from inference import InferenceError
from profiles import generation_parameters
from api_compat import apply_reasoning_budget
from api_compat import normalize_chat,CompatibilityError
from chat_media import normalize_messages,profile_capabilities
from chat_control import ChatControls,ControlError,thinking,immediate_answer
class ChatTests:
def __init__(self,profiles,worker,scheduler):
self.profiles=profiles;self.worker=worker;self.scheduler=scheduler
self.lock=threading.RLock();self.job:dict[str,Any]={};self.cancel=threading.Event();self.socket=None
self.controls=ChatControls();self.owner='admin-test-'+uuid.uuid4().hex;self.ticket=None
def status(self):
with self.lock:job=dict(self.job) if self.job else None;ticket=self.ticket
if job and ticket:
view=self.controls.view(ticket);job.update({k:v for k,v in view.items() if k!='state'});job['request_state']=view['state']
return dict(job=job,worker=self.worker.status(),scheduler=self.scheduler.status())
def capabilities(self,profile_id):
p=next((p for p in self.profiles.status()['profiles'] if p['id']==profile_id and p['kind']=='chat'),None)
if not p:raise ValueError('Chatprofil nicht gefunden.')
return profile_capabilities(self.worker,p)
def answer_now(self,data):
if not isinstance(data,dict) or set(data)!={'job_id'}:raise ControlError('Aktuelle Testauftragskennung erforderlich.')
with self.lock:
if not self.job or self.job['id']!=data['job_id'] or self.job['state']!='running' or not self.ticket:raise ControlError('Dieser Chat-Test läuft nicht mehr.',409,'not_thinking')
ticket=self.ticket
method=getattr(type(self.worker),'answer_now',None)
def send(target):
if not callable(method):raise ControlError('Jetzt antworten nicht verfügbar.',501,'answer_now_unavailable')
return method(self.worker,target)
return self.controls.request(self.owner,{'request_id':ticket},{},send)
def start(self,data):
required={'profile_id','messages','max_tokens'}
if not isinstance(data,dict) or not required<=set(data) or set(data)-required-{'session_id','reasoning_effort','logprobs','top_logprobs'}:raise ValueError('Profil, Nachrichten und Antwortlimit erforderlich; unbekannte Testoption.')
messages=data['messages'];limit=data['max_tokens']
if type(limit)!=int or not 1<=limit<=4096:raise ValueError('Antwortlimit: 1–4096 Token.')
if not isinstance(messages,list) or not 1<=len(messages)<=32:raise ValueError('1–32 Nachrichten erforderlich.')
for m in messages:
if not isinstance(m,dict) or set(m)!={'role','content'} or m['role'] not in ('user','assistant','system') or not isinstance(m['content'],(str,list)) or not m['content']:raise ValueError('Nachrichten mit Rolle user, assistant oder system und nichtleerem Inhalt erforderlich.')
if isinstance(m['content'],str) and not m['content'].strip():raise ValueError('Leere Textnachricht.')
length=sum(len(m['content']) if isinstance(m['content'],str) else sum(len(p.get('text','')) for p in m['content'] if isinstance(p,dict) and p.get('type')=='text' and isinstance(p.get('text'),str)) for m in messages)
if length>24000:raise ValueError('Testtext zu lang (maximal 24.000 Zeichen, Anhänge separat begrenzt). Neuen Chat beginnen.')
profile=next((p for p in self.profiles.status()['profiles'] if p['id']==data['profile_id'] and p['kind']=='chat'),None)
if not profile or not profile['runnable']:raise ValueError('Kein ausführbares Chatprofil. Modell und CUDA-Build prüfen.')
caps=profile_capabilities(self.worker,profile);messages,_=normalize_messages(messages,profile,caps['available'])
body=dict(model=profile.get('api_id',profile['name']),messages=messages,max_tokens=limit,stream=True,stream_options={'include_usage':True},**generation_parameters(profile['parameters']))
body.update({k:data[k] for k in ('session_id','reasoning_effort','logprobs','top_logprobs') if k in data})
try:body,_=normalize_chat(body);body=apply_reasoning_budget(body,{**profile['parameters'],'reasoning_budget':self.profiles.reasoning_budget()})
except CompatibilityError as exc:raise ValueError(str(exc)) from None
with self.lock:
if self.job and self.job['state']=='running':raise ValueError('Ein Chat-Test läuft bereits.')
ticket=self.controls.begin(self.owner,profile,session=body.pop('session_id',None),can_think=thinking(body),supported='answer_now' in caps['available']);self.ticket=ticket
self.cancel.clear();self.job=dict(id=uuid.uuid4().hex,state='running',phase='Wartet auf freie Modellreservierung',profile_id=profile['id'],profile_name=profile['name'],started_at=time.time(),answer='',reasoning='',error=None,timings={},usage={},logprobs=[])
threading.Thread(target=self._run,args=(profile,body,ticket,caps),daemon=True).start()
return dict(self.job)
def phase(self,text):
with self.lock:self.job['phase']=text
def stop(self,job_id=None):
with self.lock:
if job_id is not None and (not self.job or self.job['id']!=job_id or self.job['state']!='running'):raise ControlError('Dieser Chat-Test läuft nicht mehr.',409,'job_changed')
self.cancel.set();sock=self.socket
if sock:
try:sock.shutdown(socket.SHUT_RDWR)
except OSError:pass
return {'cancellation_requested':True}
def unload(self):
if not self.scheduler.unload_idle():raise ValueError('Es laufen noch Anfragen. Erst deren Ende abwarten; andere Antworten werden nicht abgebrochen.')
return self.status()
def _run(self,profile,body,ticket,caps):
conn=None;outcome='failed';message='Chat-Test fehlgeschlagen.';error=None
try:
key=('chat',profile['id'],profile['revision'])
def allowed():return not self.cancel.is_set() and any(p['id']==profile['id'] and p['revision']==profile['revision'] for p in self.profiles.status()['profiles'])
def prepare():
self.phase('Speicher wird geprüft · Profil wird geladen')
self.worker.ensure(profile,cancel=self.cancel.is_set)
with self.scheduler.lease(key,profile['parameters']['slots'],prepare,allowed=allowed):
if self.cancel.is_set():raise InterruptedError()
self.phase('Antwort wird erzeugt')
generation=self.worker.status().get('generation')
if self.controls.dispatch(ticket,generation):body=immediate_answer(body)
body=self.worker.prepare_request(body) if callable(getattr(type(self.worker),'prepare_request',None)) else body
headers={'Content-Type':'application/json'}
if caps.get('session_affinity'):headers.update(self.controls.headers(ticket))
elif profile['parameters'].get('chat_runtime')=='basalt':headers['X-Client-Request-Id']=ticket
if headers.get('x-session-id'):body['session_id']=headers['x-session-id']
conn,token=self.worker.connect()
conn.request('POST','/v1/chat/completions',json.dumps(body).encode(),headers={**headers,'Authorization':'Bearer '+token})
with self.lock:self.socket=conn.sock
if self.cancel.is_set():raise InterruptedError()
response=conn.getresponse()
if response.status!=200:
raise InferenceError('Das Modell-Backend hat den Test abgelehnt. Kontextbudget, Medien und Profilparameter prüfen.')
native=getattr(response,'getheader',lambda _:None)('X-Request-Id')
if isinstance(native,str) and native:self.controls.bind(ticket,native)
method=getattr(type(self.worker),'answer_now',None)
def send(target):
if not callable(method):raise ControlError('Jetzt antworten nicht verfügbar.',501,'answer_now_unavailable')
return method(self.worker,target)
self.controls.started(ticket,generation,send)
buffer=b'';total=0;done=False;deadline=time.monotonic()+600
while time.monotonic()<deadline:
if self.cancel.is_set():raise InterruptedError()
chunk=response.read1(8192)
if not chunk:break
buffer+=chunk;total+=len(chunk)
if total>4*1024**2:raise InferenceError('Testantwort überschreitet 4 MiB.')
while b'\n' in buffer:
line,buffer=buffer.split(b'\n',1);line=line.strip()
if not line.startswith(b'data:'):continue
payload=line[5:].strip()
if payload==b'[DONE]':done=True;break
event=json.loads(payload)
if 'error' in event:raise InferenceError('Der Modellworker meldet einen Fehler während der Antwort.')
with self.lock:
for section,fields in [('timings',('prompt_n','prompt_ms','prompt_per_second','predicted_n','predicted_ms','predicted_per_second')),('usage',('prompt_tokens','completion_tokens','total_tokens'))]:
values=event.get(section)
if isinstance(values,dict):
self.job[section]={k:v for k,v in values.items() if k in fields and type(v) in (int,float) and math.isfinite(v) and v>=0}
for choice in event.get('choices',[]):
delta=choice.get('delta',{})
if delta.get('content'):self.controls.answering(ticket)
with self.lock:
for source,target in [('content','answer'),('reasoning_content','reasoning')]:
if isinstance(delta.get(source),str):self.job[target]+=delta[source]
if choice.get('finish_reason'):self.job['finish_reason']=choice['finish_reason']
logprobs=choice.get('logprobs')
if body.get('logprobs') and isinstance(logprobs,dict) and isinstance(logprobs.get('content'),list):self.job['logprobs']=(self.job['logprobs']+logprobs['content'])[-512:]
if done:break
if not done:raise InferenceError('Antwort unterbrochen oder Zeitlimit erreicht. '+(self.worker.status().get('error') or 'Ein GPU-OOM ist ohne eindeutigen Nachweis nicht bestätigt.'))
outcome='complete';message='Antwort fertig · Modell bleibt für weitere Anfragen geladen'
except Exception as exc:
cancelled=self.cancel.is_set()
message='Chat-Test abgebrochen.' if cancelled else (str(exc) if isinstance(exc,InferenceError) else 'Verbindung zum Modell unterbrochen. '+(self.worker.status().get('error') or 'Speicherfehler, Modellabsturz oder Zeitlimit möglich; Ursache nicht eindeutig.'))
outcome='cancelled' if cancelled else 'failed';error=None if cancelled else message
finally:
if conn:conn.close()
self.controls.finish(ticket)
with self.lock:self.socket=None;self.job.update(state=outcome,error=error,phase=message,finished_at=time.time())