Files
Athena-Deck/responses_compat.py
T

225 lines
18 KiB
Python

"""Stateless Responses-to-Chat compatibility; no extra server or credentials."""
import codecs
import json
import re
import time
import uuid
from typing import Any
class ResponsesError(ValueError):pass
def ident(prefix):return prefix+'_'+uuid.uuid4().hex
def translate(body):
allowed={'model','input','instructions','tools','tool_choice','parallel_tool_calls','reasoning','text','stream','store','include','max_output_tokens','temperature','top_p','metadata','user','service_tier','prompt_cache_key','prompt_cache_retention','safety_identifier','truncation','session_id','top_logprobs'}
if not isinstance(body,dict):raise ResponsesError('Responses-Anfrage muss ein JSON-Objekt sein.')
if set(body)-allowed:raise ResponsesError('Nicht unterstützte Responses-Felder: '+', '.join(sorted(set(body)-allowed)))
if type(body.get('stream',False)) is not bool:raise ResponsesError('stream muss true oder false sein.')
if body.get('store',False) is not False:raise ResponsesError('Nur store=false unterstützt; Gesprächskontext vollständig mitsenden.')
if body.get('truncation','disabled')!='disabled':raise ResponsesError('Automatische Kontextkürzung wird nicht unterstützt.')
if body.get('service_tier','auto') not in ('auto','default'):raise ResponsesError('Keine besonderen Service-Tiers unterstützt.')
include=body.get('include',[])
if include is None:include=[]
if not isinstance(include,list) or len(include)>16 or any(not isinstance(x,str) for x in include):raise ResponsesError('include muss eine Liste von Feldnamen sein.')
want_logprobs='message.output_text.logprobs' in include
mapping={};tools=[]
def add(tool,namespace=None):
if not isinstance(tool,dict) or tool.get('type') not in ('function','custom'):raise ResponsesError('Nur Function- und Custom-Werkzeuge unterstützt.')
name=tool.get('name')
if not isinstance(name,str):raise ResponsesError('Werkzeugname fehlt.')
flat=(namespace+'__' if namespace else '')+name
if not re.fullmatch(r'[A-Za-z0-9_-]{1,64}',flat) or flat in mapping:raise ResponsesError('Ungültiger oder mehrfacher Werkzeugname.')
mapping[flat]=dict(name=name,type=tool['type'],**({'namespace':namespace} if namespace else {}))
params=tool.get('parameters',{'type':'object','properties':{}})
if tool['type']=='custom':params=dict(type='object',properties={'input':dict(type='string',description='Exact freeform input, including newlines.')},required=['input'],additionalProperties=False)
tools.append(dict(type='function',function=dict(name=flat,description=tool.get('description',''),parameters=params)))
definitions=body.get('tools',[])
if not isinstance(definitions,list):raise ResponsesError('tools muss eine Liste sein.')
for tool in definitions:
if isinstance(tool,dict) and tool.get('type')=='namespace':
namespace=tool.get('name');nested=tool.get('tools')
if not isinstance(namespace,str) or not isinstance(nested,list):raise ResponsesError('Ungültiger Werkzeug-Namespace.')
for t in nested:add(t,namespace)
else:add(tool)
source=body.get('input',[])
if isinstance(source,str):source=[dict(role='user',content=source)]
if not isinstance(source,list):raise ResponsesError('input muss Text oder eine Liste sein.')
messages=[];systems=[]
if body.get('instructions'):
if not isinstance(body['instructions'],str):raise ResponsesError('instructions muss Text sein.')
systems.append(body['instructions'])
def content_parts(content):
parts=[]
for part in content:
if not isinstance(part,dict):raise ResponsesError('Ungültiger Nachrichteninhalt.')
kind=part.get('type')
if kind in ('input_text','output_text') and isinstance(part.get('text'),str):parts.append(dict(type='text',text=part['text']))
elif kind=='input_image':parts.append(dict(type='image_url',image_url={'url':part.get('image_url')}))
elif kind=='input_file':
if set(part)-{'type','filename','file_data','pages'} or not {'filename','file_data'}<=set(part):raise ResponsesError('input_file benötigt eingebettete file_data und filename; keine Datei-IDs oder URLs.')
parts.append({'type':'file','file':{k:v for k,v in part.items() if k!='type'}})
elif kind=='input_video':
if set(part)-{'type','video_url','fps','max_frames'} or not isinstance(part.get('video_url'),str):raise ResponsesError('input_video benötigt eine eingebettete Video-Daten-URL.')
parts.append({'type':'video_url','video_url':{'url':part['video_url']},**{k:part[k] for k in ('fps','max_frames') if k in part}})
else:raise ResponsesError('Nicht unterstützter Nachrichteninhalt.')
return '\n'.join(p['text'] for p in parts) if all(p['type']=='text' for p in parts) else parts
for item in source:
if not isinstance(item,dict):raise ResponsesError('Ungültiges input-Element.')
kind=item.get('type','message')
if kind=='reasoning':continue
if kind in ('function_call','custom_tool_call'):
name=item.get('name');call_id=item.get('call_id')
if not isinstance(name,str) or not isinstance(call_id,str):raise ResponsesError('Werkzeugname und call_id erforderlich.')
if item.get('namespace'):name=item['namespace']+'__'+name
args=json.dumps({'input':item.get('input')}) if kind=='custom_tool_call' else item.get('arguments')
if not isinstance(args,str):raise ResponsesError('arguments muss JSON-Text sein.')
call=dict(id=call_id,type='function',function=dict(name=name,arguments=args))
if messages and messages[-1].get('tool_calls'):messages[-1]['tool_calls'].append(call)
else:messages.append(dict(role='assistant',content=None,tool_calls=[call]))
elif kind in ('function_call_output','custom_tool_call_output'):
if not isinstance(item.get('call_id'),str):raise ResponsesError('call_id fehlt.')
output=item.get('output','')
typed=isinstance(output,list) and bool(output) and all(isinstance(x,dict) and 'type' in x for x in output)
messages.append(dict(role='tool',tool_call_id=item['call_id'],content=content_parts(output) if typed else output if isinstance(output,str) else json.dumps(output)))
elif kind=='message':
role=item.get('role','user');content=item.get('content','')
if role not in ('developer','system','user','assistant'):raise ResponsesError('Nicht unterstützte Nachrichtenrolle.')
if isinstance(content,list):
content=content_parts(content)
if not isinstance(content,(str,list)):raise ResponsesError('Ungültiger Nachrichteninhalt.')
if role in ('system','developer'):
if not isinstance(content,str):raise ResponsesError('Systemanweisungen müssen Text sein.')
systems.append(content)
else:messages.append(dict(role=role,content=content))
else:raise ResponsesError('Nicht unterstütztes input-Element: '+str(kind))
# Qwen rejects later system/developer messages. Keep their order and content.
if systems:messages.insert(0,dict(role='system',content='\n\n'.join(systems)))
chat=dict(model=body.get('model'),messages=messages,stream=body.get('stream',False))
if chat['stream']:chat['stream_options']={'include_usage':True}
if tools:chat['tools']=tools
for field in ('temperature','top_p','parallel_tool_calls','user','session_id'):
if field in body:chat[field]=body[field]
if 'max_output_tokens' in body:chat['max_tokens']=body['max_output_tokens']
if want_logprobs:chat['logprobs']=True
if 'top_logprobs' in body:
if not want_logprobs:raise ResponsesError('top_logprobs benötigt include=message.output_text.logprobs.')
chat['top_logprobs']=body['top_logprobs']
reasoning=body.get('reasoning',{})
if not isinstance(reasoning,dict) or set(reasoning)-{'effort','summary'}:raise ResponsesError('Nicht unterstützte reasoning-Einstellungen.')
if 'effort' in reasoning:chat['reasoning_effort']=reasoning['effort']
text=body.get('text',{})
if not isinstance(text,dict) or set(text)-{'format','verbosity'}:raise ResponsesError('Nicht unterstützte text-Einstellungen.')
format_=text.get('format',{'type':'text'})
if not isinstance(format_,dict) or format_.get('type')!='text':raise ResponsesError('Zunächst nur Textausgabe unterstützt.')
choice=body.get('tool_choice')
if choice is not None:
if isinstance(choice,str):chat['tool_choice']=choice
elif isinstance(choice,dict) and choice.get('type') in ('function','custom') and isinstance(choice.get('name'),str):
name=(choice.get('namespace','')+'__' if choice.get('namespace') else '')+choice['name']
chat['tool_choice']=dict(type='function',function={'name':name})
else:raise ResponsesError('Nicht unterstütztes tool_choice.')
return chat,Converter(body.get('model'),mapping,want_logprobs)
class Converter:
def __init__(self,model,mapping,want_logprobs=False):
self.mapping=mapping;self.seq=0;self.pending='';self.decoder=codecs.getincrementaldecoder('utf8')();self.lines=[];self.done=False;self.reason=None;self.calls={};self.usage={}
self.text:dict[str,Any]|None=None;self.thinking:dict[str,Any]|None=None
self.text_lps=[];self.reasoning_lps=[];self.tool_lps={}
self.response=dict(id=ident('resp'),object='response',created_at=int(time.time()),status='in_progress',model=model,output=[],error=None,incomplete_details=None,usage=None)
self.want_logprobs=want_logprobs
def event(self,type_,**data):
value=dict(type=type_,sequence_number=self.seq,**data);self.seq+=1
return ('event: '+type_+'\ndata: '+json.dumps(value,ensure_ascii=False)+'\n\n').encode()
def start(self):return self.event('response.created',response=self.response)+self.event('response.in_progress',response=self.response)
def add(self,item):
index=len(self.response['output']);self.response['output'].append(item)
return index,self.event('response.output_item.added',output_index=index,item=item)
def delta(self,delta,logprobs=None):
out=b'';thinking=delta.get('reasoning_content') or delta.get('reasoning')
entries=[]
if self.want_logprobs and isinstance(logprobs,dict):
entries=logprobs.get('content',[]);reasoning_entries=logprobs.get('reasoning_content',[]);tools=logprobs.get('tool_calls',[])
if not isinstance(entries,list) or not isinstance(reasoning_entries,list) or not isinstance(tools,list):raise ResponsesError('Ungültige Tokenwahrscheinlichkeiten im Modellstream.')
self.text_lps.extend(entries);self.reasoning_lps.extend(reasoning_entries)
for tool in tools:
if not isinstance(tool,dict) or type(tool.get('index')) is not int or tool['index']<0 or not isinstance(tool.get('content'),list):raise ResponsesError('Ungültige Werkzeugwahrscheinlichkeiten im Modellstream.')
self.tool_lps.setdefault(tool['index'],[]).extend(tool['content'])
if thinking:
if not self.thinking:
self.thinking=dict(id=ident('rs'),type='reasoning',summary=[dict(type='summary_text',text='')]);self.thinking_index,added=self.add(self.thinking);out+=added
if self.want_logprobs:self.thinking['logprobs']=self.reasoning_lps
out+=self.event('response.reasoning_summary_part.added',item_id=self.thinking['id'],output_index=self.thinking_index,summary_index=0,part=self.thinking['summary'][0])
self.thinking['summary'][0]['text']+=thinking
out+=self.event('response.reasoning_summary_text.delta',item_id=self.thinking['id'],output_index=self.thinking_index,summary_index=0,delta=thinking)
if delta.get('content'):
if not self.text:
self.text=dict(id=ident('msg'),type='message',role='assistant',status='in_progress',content=[dict(type='output_text',text='',annotations=[])]);self.text_index,added=self.add(self.text);out+=added
if self.want_logprobs:self.text['content'][0]['logprobs']=self.text_lps
out+=self.event('response.content_part.added',item_id=self.text['id'],output_index=self.text_index,content_index=0,part=self.text['content'][0])
self.text['content'][0]['text']+=delta['content']
out+=self.event('response.output_text.delta',item_id=self.text['id'],output_index=self.text_index,content_index=0,delta=delta['content'],**({'logprobs':entries} if self.want_logprobs else {}))
for value in delta.get('tool_calls',[]):
call=self.calls.setdefault(value['index'],dict(id=ident('fc'),type='function_call',status='in_progress',call_id='',name='',arguments=''))
if self.want_logprobs:call['logprobs']=self.tool_lps.setdefault(value['index'],[])
if value.get('id'):call['call_id']=value['id']
call['name']+=value.get('function',{}).get('name','');call['arguments']+=value.get('function',{}).get('arguments','')
return out
def feed(self,chunk):
self.pending+=self.decoder.decode(chunk);out=b''
while '\n' in self.pending:
line,self.pending=self.pending.split('\n',1);line=line.rstrip('\r')
if line.startswith('data:'):self.lines.append(line[5:].lstrip())
elif not line and self.lines:
raw='\n'.join(self.lines);self.lines=[]
if raw=='[DONE]':self.done=True;continue
value=json.loads(raw)
if value.get('error'):raise ResponsesError('Modellstream meldet einen Fehler.')
self.usage=value.get('usage') or self.usage
for choice in value.get('choices',[]):
out+=self.delta(choice.get('delta',{}),choice.get('logprobs'));self.reason=choice.get('finish_reason') or self.reason
return out
def finish(self):
if not self.done or not self.reason:raise ResponsesError('Modellstream vorzeitig abgebrochen.')
out=b''
if self.thinking:
out+=self.event('response.reasoning_summary_text.done',item_id=self.thinking['id'],output_index=self.thinking_index,summary_index=0,text=self.thinking['summary'][0]['text'])
out+=self.event('response.reasoning_summary_part.done',item_id=self.thinking['id'],output_index=self.thinking_index,summary_index=0,part=self.thinking['summary'][0])
out+=self.event('response.output_item.done',output_index=self.thinking_index,item=self.thinking)
if self.text:
self.text['status']='completed'
out+=self.event('response.output_text.done',item_id=self.text['id'],output_index=self.text_index,content_index=0,text=self.text['content'][0]['text'],**({'logprobs':self.text_lps} if self.want_logprobs else {}))
out+=self.event('response.content_part.done',item_id=self.text['id'],output_index=self.text_index,content_index=0,part=self.text['content'][0])
out+=self.event('response.output_item.done',output_index=self.text_index,item=self.text)
for call in self.calls.values():
original=self.mapping.get(call['name'])
if not original or not call['call_id']:raise ResponsesError('Unbekannter Werkzeugaufruf oder fehlende call_id.')
call['name']=original['name']
if original.get('namespace'):call['namespace']=original['namespace']
args=call.pop('arguments') if original['type']=='custom' else call['arguments']
if original['type']=='custom':
input_=json.loads(args).get('input')
if not isinstance(input_,str):raise ResponsesError('Custom-Werkzeug benötigt Textinput.')
call.update(type='custom_tool_call',input='');index,added=self.add(call);out+=added;call['input']=input_
out+=self.event('response.custom_tool_call_input.delta',item_id=call['id'],output_index=index,delta=input_)
out+=self.event('response.custom_tool_call_input.done',item_id=call['id'],output_index=index,input=input_)
else:
call['arguments']='';index,added=self.add(call);out+=added;call['arguments']=args
out+=self.event('response.function_call_arguments.delta',item_id=call['id'],output_index=index,delta=args)
out+=self.event('response.function_call_arguments.done',item_id=call['id'],output_index=index,arguments=args)
call['status']='completed';out+=self.event('response.output_item.done',output_index=index,item=call)
u=self.usage
self.response['usage']=dict(input_tokens=u.get('prompt_tokens',0),output_tokens=u.get('completion_tokens',0),total_tokens=u.get('total_tokens',0),input_tokens_details=dict(cached_tokens=(u.get('prompt_tokens_details') or {}).get('cached_tokens',0)),output_tokens_details=dict(reasoning_tokens=(u.get('completion_tokens_details') or {}).get('reasoning_tokens',0)))
self.response['status']='incomplete' if self.reason in ('length','content_filter') else 'completed'
if self.response['status']=='incomplete':self.response['incomplete_details']={'reason':'max_output_tokens' if self.reason=='length' else 'content_filter'}
return out+self.event('response.'+self.response['status'],response=self.response)
def complete(self,value):
choices=value.get('choices',[])
if not choices:raise ResponsesError('Leere Modellantwort.')
message=choices[0].get('message',{});delta=dict(message)
delta['tool_calls']=[dict(c,index=i) for i,c in enumerate(message.get('tool_calls',[]))]
self.delta(delta,choices[0].get('logprobs'));self.reason=choices[0].get('finish_reason') or 'stop';self.usage=value.get('usage') or {};self.done=True;self.finish()
return self.response
def failure(self):
self.response.update(status='failed',error=dict(code='upstream_stream_error',message='Responses-Stream konnte nicht vollständig verarbeitet werden.'))
return self.event('response.failed',response=self.response)