"""Stateless Responses-to-Chat compatibility; no extra server or credentials.""" import codecs import json import re import time import uuid 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'} 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.') 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']) 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','') messages.append(dict(role='tool',tool_call_id=item['call_id'],content=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): parts=[] for part in content: if not isinstance(part,dict):raise ResponsesError('Ungültiger Nachrichteninhalt.') if part.get('type') in ('input_text','output_text') and isinstance(part.get('text'),str):parts.append(dict(type='text',text=part['text'])) elif part.get('type')=='input_image':parts.append(dict(type='image_url',image_url={'url':part.get('image_url')})) else:raise ResponsesError('Nicht unterstützter Nachrichteninhalt.') content='\n'.join(p['text'] for p in parts) if all(p['type']=='text' for p in parts) else parts 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'): if field in body:chat[field]=body[field] if 'max_output_tokens' in body:chat['max_tokens']=body['max_output_tokens'] 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) class Converter: def __init__(self,model,mapping): self.mapping=mapping;self.seq=0;self.pending='';self.decoder=codecs.getincrementaldecoder('utf8')();self.lines=[];self.done=False;self.reason=None;self.calls={};self.text=None;self.thinking=None;self.usage={} 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) 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): out=b'';thinking=delta.get('reasoning_content') or delta.get('reasoning') 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 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 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']) 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 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',{}));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']) 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);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)