From 650eb398c6138ce0fa3425da9f93d4c5cf57229d Mon Sep 17 00:00:00 2001 From: Mikei386 <44135113+Mikei386@users.noreply.github.com> Date: Sun, 4 Oct 2026 10:38:10 +0200 Subject: [PATCH] Add switchable stateless Responses API compatibility --- RESPONSES_COMPATIBILITY.md | 73 +++++++++++++ backup.py | 2 +- deploy/Dockerfile | 2 +- deploy/Dockerfile.app-update | 2 +- deploy/install.py | 2 +- endpoint-ui.js | 5 +- endpoint.py | 47 +++++++-- responses_compat.py | 191 +++++++++++++++++++++++++++++++++++ test_backup.py | 4 + test_endpoint.py | 27 ++++- test_responses_compat.py | 39 +++++++ 11 files changed, 376 insertions(+), 18 deletions(-) create mode 100644 RESPONSES_COMPATIBILITY.md create mode 100644 responses_compat.py create mode 100644 test_responses_compat.py diff --git a/RESPONSES_COMPATIBILITY.md b/RESPONSES_COMPATIBILITY.md new file mode 100644 index 0000000..737e996 --- /dev/null +++ b/RESPONSES_COMPATIBILITY.md @@ -0,0 +1,73 @@ +# Optional Responses compatibility + +In **Settings → API**, enable **Responses-API aktivieren**. The default is off. +The setting can change while the endpoint is running. Disabling rejects new +Responses requests; already admitted requests finish normally. Existing Chat +Completions requests and profiles retain their behavior. + +Enabled: `POST /v1/responses` on the existing API port and with the existing +Bearer token. The request uses the same enabled Chat profiles, worker, GPU +scheduler, slot accounting and network access policy as `/v1/chat/completions`. +There is no additional service, listener, token store or model runtime. + +`GET /v1/capabilities` reports the switch and boundaries. The setting is stored +as `responses_compat` in `endpoint.json` and included in encrypted backup/restore. +Older settings and backups default to disabled. + +## Supported subset + +- Stateless requests with complete replayed input, string or message input. +- Text replies, incremental SSE, reasoning text and usage when supplied upstream. +- Function tools, tool namespaces, matching call IDs and tool-result replay. +- Custom/freeform tools translated to a function with a string `input` property; + freeform decoding grammars are not enforced by this conversion. +- Embedded image input forwarded to the existing Vision validation and projector. + This is not a qualification of every model's Vision implementation. +- Client sampling values and explicitly requested output limits are forwarded; + compatibility does not add an output-token cap. Profile defaults apply normally. + +System/developer updates are concatenated in chronological order into one leading +system message. This accommodates Qwen templates rejecting later system messages +(`System message must be at the beginning`). This normalization only applies to +Responses requests, not ordinary Chat Completions traffic. + +Unsupported: stored response retrieval, `previous_response_id`, WebSocket +continuation, hosted OpenAI tools, automatic truncation, structured output formats +and multimodal generation. Unsupported semantics return an actionable error rather +than silently dropping them. No extra model capability is created by this adapter. +All existing endpoint size, timeout and Vision constraints still apply. + +## ChatGPT local client + +Use an isolated test profile first. Provider example: + +```toml +model = "" +model_provider = "athena" +web_search = "disabled" + +[features] +enable_request_compression = false + +[model_providers.athena] +name = "Athena Deck" +base_url = "http://:8120/v1" +wire_api = "responses" +env_key = "ATHENA_API_TOKEN" +requires_openai_auth = false +supports_websockets = false +``` + +Provide the token via the client's environment/secret mechanism, not Git or TOML. +Supply a custom model catalog matching Athena's IDs, per-slot contexts and actual +capabilities. The model catalog is client metadata and is not replaced by this +server adapter. Cloud ChatGPT capabilities are not routed through this API. + +After switching the client directly to Athena, qualify text, streaming, a harmless +tool loop and a follow-up before stopping the old local adapter. Do not assume a +successful text reply establishes every desktop feature. + +Official references: [Custom gateway setup](https://learn.chatgpt.com/docs/enterprise/connect-to-a-gateway), +[Required Responses behavior](https://learn.chatgpt.com/docs/enterprise/gateway-compatibility). + +Tests: `python3 -m unittest test_responses_compat test_endpoint test_api_compat test_backup`. diff --git a/backup.py b/backup.py index 584da4c..8e16563 100644 --- a/backup.py +++ b/backup.py @@ -78,7 +78,7 @@ def validate(doc): settings=doc.get('settings') if not isinstance(settings,dict) or set(settings)-set(SETTINGS):raise ValueError('Unbekannte Einstellungsdateien.') ep=settings.get('endpoint.json',{}) - if not isinstance(ep,dict) or set(ep)-{'port','enabled_profiles','autostart'} or type(ep.get('port',8120)) is not int or not 1024<=ep.get('port',8120)<=65535 or type(ep.get('autostart',False)) is not bool:raise ValueError('Ungültige Endpunkt-Einstellungen.') + if not isinstance(ep,dict) or set(ep)-{'port','enabled_profiles','autostart','responses_compat'} or type(ep.get('responses_compat',False)) is not bool or type(ep.get('port',8120)) is not int or not 1024<=ep.get('port',8120)<=65535 or type(ep.get('autostart',False)) is not bool:raise ValueError('Ungültige Endpunkt-Einstellungen.') enabled=ep.get('enabled_profiles',[]) if not isinstance(enabled,list) or any(p not in pids for p in enabled) or len(set(enabled))!=len(enabled):raise ValueError('Unbekannte Profilfreigabe.') if sum(p['kind']=='image' and p['id'] in enabled for p in profiles)>1:raise ValueError('Nur ein Bildprofil darf freigegeben sein.') diff --git a/deploy/Dockerfile b/deploy/Dockerfile index 202f404..d5ad039 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -16,7 +16,7 @@ WORKDIR /app COPY deploy/image-requirements.lock /app/deploy/image-requirements.lock COPY deploy/tts-requirements.lock /app/deploy/tts-requirements.lock COPY deploy/ltx-original-requirements.lock /app/deploy/ltx-original-requirements.lock -COPY embeddings.py voxcpm_test.py voxcpm_worker.py voxcpm_runtime.py separator_sources.json separator.py separator_runtime.py separator_worker.py music.py audio_cpp_runtime.py ltx_original_runtime.py ltx_original_entry.py video_original.py backup.py backup_codec.py audio_policy.py prompt_enhancer.py prompt_enhancer_worker.py api_compat.py stt.py execution_setup.py tts_runtime.py tts_test.py tts_worker.py auto_test.py chat_test.py endpoint.py inference.py docker_support.py image_encoder_node.py image_runtime.py image_test.py image_upload.py profiles.py capacity.py server.py runtime.py video.py video_proxy.py video_comfy.py video_comfy_node.py video_comfy_proxy.py catalog.py hub_auth.py auth.py collect_hardware.py dashboard_data.py dashboard_history.py /app/ +COPY embeddings.py voxcpm_test.py voxcpm_worker.py voxcpm_runtime.py separator_sources.json separator.py separator_runtime.py separator_worker.py music.py audio_cpp_runtime.py ltx_original_runtime.py ltx_original_entry.py video_original.py backup.py backup_codec.py audio_policy.py prompt_enhancer.py prompt_enhancer_worker.py api_compat.py responses_compat.py stt.py execution_setup.py tts_runtime.py tts_test.py tts_worker.py auto_test.py chat_test.py endpoint.py inference.py docker_support.py image_encoder_node.py image_runtime.py image_test.py image_upload.py profiles.py capacity.py server.py runtime.py video.py video_proxy.py video_comfy.py video_comfy_node.py video_comfy_proxy.py catalog.py hub_auth.py auth.py collect_hardware.py dashboard_data.py dashboard_history.py /app/ COPY voice-ui.js voxcpm-ui.js separator-ui.js music-ui.js audio-cpp-ui.js ltx-original-ui.js backup-ui.js video-ui.js stt-ui.js tts-ui.js auto-test-ui.js chat-test-ui.js endpoint-ui.js docker-ui.js image-test-ui.js profiles-ui.js dashboard-ui.js index.html app.js studio.js runtime-ui.js catalog-ui.js style.css dashboard.css themes.css login.html login.js access-ui.js network-ui.js /app/ COPY deploy/docker_backup.py /app/deploy/docker_backup.py COPY network/__init__.py network/client.py network/config.py network/rpc.py /app/network/ diff --git a/deploy/Dockerfile.app-update b/deploy/Dockerfile.app-update index 667fdb8..8c2d202 100644 --- a/deploy/Dockerfile.app-update +++ b/deploy/Dockerfile.app-update @@ -6,7 +6,7 @@ WORKDIR /app COPY deploy/image-requirements.lock /app/deploy/image-requirements.lock COPY deploy/tts-requirements.lock /app/deploy/tts-requirements.lock COPY deploy/ltx-original-requirements.lock /app/deploy/ltx-original-requirements.lock -COPY embeddings.py voxcpm_test.py voxcpm_worker.py voxcpm_runtime.py separator_sources.json separator.py separator_runtime.py separator_worker.py music.py audio_cpp_runtime.py ltx_original_runtime.py ltx_original_entry.py video_original.py backup.py backup_codec.py audio_policy.py prompt_enhancer.py prompt_enhancer_worker.py api_compat.py stt.py execution_setup.py tts_runtime.py tts_test.py tts_worker.py auto_test.py chat_test.py endpoint.py inference.py docker_support.py image_encoder_node.py image_runtime.py image_test.py image_upload.py profiles.py capacity.py server.py runtime.py video.py video_proxy.py video_comfy.py video_comfy_node.py video_comfy_proxy.py catalog.py hub_auth.py auth.py collect_hardware.py dashboard_data.py dashboard_history.py /app/ +COPY embeddings.py voxcpm_test.py voxcpm_worker.py voxcpm_runtime.py separator_sources.json separator.py separator_runtime.py separator_worker.py music.py audio_cpp_runtime.py ltx_original_runtime.py ltx_original_entry.py video_original.py backup.py backup_codec.py audio_policy.py prompt_enhancer.py prompt_enhancer_worker.py api_compat.py responses_compat.py stt.py execution_setup.py tts_runtime.py tts_test.py tts_worker.py auto_test.py chat_test.py endpoint.py inference.py docker_support.py image_encoder_node.py image_runtime.py image_test.py image_upload.py profiles.py capacity.py server.py runtime.py video.py video_proxy.py video_comfy.py video_comfy_node.py video_comfy_proxy.py catalog.py hub_auth.py auth.py collect_hardware.py dashboard_data.py dashboard_history.py /app/ COPY voice-ui.js voxcpm-ui.js separator-ui.js music-ui.js audio-cpp-ui.js ltx-original-ui.js backup-ui.js video-ui.js stt-ui.js tts-ui.js auto-test-ui.js chat-test-ui.js endpoint-ui.js docker-ui.js image-test-ui.js profiles-ui.js dashboard-ui.js index.html app.js studio.js runtime-ui.js catalog-ui.js style.css dashboard.css themes.css login.html login.js access-ui.js network-ui.js /app/ COPY deploy/docker_backup.py /app/deploy/docker_backup.py COPY network/__init__.py network/client.py network/config.py network/rpc.py /app/network/ diff --git a/deploy/install.py b/deploy/install.py index d8f109d..9ecccc9 100644 --- a/deploy/install.py +++ b/deploy/install.py @@ -14,7 +14,7 @@ import urllib.request ROOT = Path(__file__).resolve().parent.parent LABEL = 'de.casaderoll.athena-deck.standalone' -FILES = ['embeddings.py','voxcpm_test.py','voxcpm_worker.py','voice-ui.js','voxcpm_runtime.py','voxcpm-ui.js','deploy/voxcpm-requirements.lock','network/native.py','deploy/setup_network_helper.py','separator_sources.json','deploy/separator-web/Dockerfile','deploy/separator-web/app.py','deploy/separator-web/index.html','separator.py','separator_runtime.py','separator_worker.py','separator-ui.js','deploy/ladypoly/Dockerfile','deploy/ladypoly/bridge.py','music.py','music-ui.js','audio_cpp_runtime.py','audio-cpp-ui.js','ltx_original_runtime.py','ltx_original_entry.py','video_original.py','ltx-original-ui.js','deploy/ltx-original-requirements.lock','backup.py','backup_codec.py','backup-ui.js','deploy/docker_backup.py','deploy/swarm-ui/Dockerfile','deploy/swarm-ui/patch-source.py','deploy/swarm-ui/proxy.py','deploy/swarm-ui/entrypoint.py','deploy/Dockerfile.app-update','video_comfy.py','video_comfy_node.py','video_comfy_proxy.py','prompt_enhancer.py','prompt_enhancer_worker.py','image_upload.py','audio_policy.py','deploy/tts-requirements.lock','stt.py','stt-ui.js','api_compat.py','execution_setup.py','tts_runtime.py','tts_test.py','tts_worker.py','tts-ui.js','auto_test.py','auto-test-ui.js','chat_test.py','chat-test-ui.js','endpoint.py','inference.py','endpoint-ui.js','docker_support.py','docker-ui.js','deploy/docker_helper.py','deploy/setup_docker_helper.py','image_encoder_node.py','image_runtime.py','image_test.py','image-test-ui.js','profiles.py','profiles-ui.js','capacity.py','runtime.py','runtime-ui.js','video.py','video_proxy.py','video-ui.js','catalog.py','hub_auth.py','catalog-ui.js','server.py','auth.py','collect_hardware.py','dashboard_data.py','dashboard_history.py','dashboard-ui.js','dashboard.css','themes.css','deploy/import_dashboard_history.py','index.html','app.js','studio.js','style.css','login.html','login.js','access-ui.js','network-ui.js','network/__init__.py','network/client.py','network/config.py','network/rpc.py','deploy/Dockerfile','deploy/image-requirements.lock'] +FILES = ['embeddings.py','voxcpm_test.py','voxcpm_worker.py','voice-ui.js','voxcpm_runtime.py','voxcpm-ui.js','deploy/voxcpm-requirements.lock','network/native.py','deploy/setup_network_helper.py','separator_sources.json','deploy/separator-web/Dockerfile','deploy/separator-web/app.py','deploy/separator-web/index.html','separator.py','separator_runtime.py','separator_worker.py','separator-ui.js','deploy/ladypoly/Dockerfile','deploy/ladypoly/bridge.py','music.py','music-ui.js','audio_cpp_runtime.py','audio-cpp-ui.js','ltx_original_runtime.py','ltx_original_entry.py','video_original.py','ltx-original-ui.js','deploy/ltx-original-requirements.lock','backup.py','backup_codec.py','backup-ui.js','deploy/docker_backup.py','deploy/swarm-ui/Dockerfile','deploy/swarm-ui/patch-source.py','deploy/swarm-ui/proxy.py','deploy/swarm-ui/entrypoint.py','deploy/Dockerfile.app-update','video_comfy.py','video_comfy_node.py','video_comfy_proxy.py','prompt_enhancer.py','prompt_enhancer_worker.py','image_upload.py','audio_policy.py','deploy/tts-requirements.lock','stt.py','stt-ui.js','api_compat.py','responses_compat.py','execution_setup.py','tts_runtime.py','tts_test.py','tts_worker.py','tts-ui.js','auto_test.py','auto-test-ui.js','chat_test.py','chat-test-ui.js','endpoint.py','inference.py','endpoint-ui.js','docker_support.py','docker-ui.js','deploy/docker_helper.py','deploy/setup_docker_helper.py','image_encoder_node.py','image_runtime.py','image_test.py','image-test-ui.js','profiles.py','profiles-ui.js','capacity.py','runtime.py','runtime-ui.js','video.py','video_proxy.py','video-ui.js','catalog.py','hub_auth.py','catalog-ui.js','server.py','auth.py','collect_hardware.py','dashboard_data.py','dashboard_history.py','dashboard-ui.js','dashboard.css','themes.css','deploy/import_dashboard_history.py','index.html','app.js','studio.js','style.css','login.html','login.js','access-ui.js','network-ui.js','network/__init__.py','network/client.py','network/config.py','network/rpc.py','deploy/Dockerfile','deploy/image-requirements.lock'] def run(*args, check=True, interactive=False): diff --git a/endpoint-ui.js b/endpoint-ui.js index e80aebb..13c9b1e 100644 --- a/endpoint-ui.js +++ b/endpoint-ui.js @@ -47,9 +47,10 @@ window.EndpointUI=(()=>{ async function render(settings=false){ const view=document.querySelector('#view');let root=view.querySelector('#endpoint-page'); if(!root||root.dataset.settings!==String(settings)){ - sequence++;clearTimeout(controlTimer);selectedMode=null;view.innerHTML=`
${settings?'EINSTELLUNGEN / API':'ATHENA DECK / ROUTER'}

${settings?'Endpunkt':'Steuerung'}

${settings?'

API-Port und freigegebene Profile verwalten.

':'

Betriebsart wählen und starten.

'}

${settings?'

Lokaler API-Port

Der Zugriff verwendet den API-Token aus Zugang & API-Token. Verwaltungsoberfläche und API haben getrennte Ports.

Am Endpunkt angebotene Profile

Nur explizit aktivierte, ausführbare Profile erscheinen in GET /v1/models. Aktivieren lädt noch kein Modell.

API-Routen

POST /v1/chat/completions · Text und Streaming
POST /v1/images/generations · Qwen-Image-Rezept, ein Bild als b64_json
POST /v1/audio/speech und POST /v1/audio/transcriptions · noch nicht eingerichtet (501)

Alle Routen nutzen denselben Port und Bearer-Token. Bei Bildaufträgen bestimmt das Profil Auflösung, Schritte, Guidance und Seed. Noch keine Bildbearbeitung oder Vision-Eingaben.

':''}
`; + sequence++;clearTimeout(controlTimer);selectedMode=null;view.innerHTML=`
${settings?'EINSTELLUNGEN / API':'ATHENA DECK / ROUTER'}

${settings?'Endpunkt':'Steuerung'}

${settings?'

API-Port und freigegebene Profile verwalten.

':'

Betriebsart wählen und starten.

'}

${settings?'

Lokaler API-Port

Der Zugriff verwendet den API-Token aus Zugang & API-Token. Verwaltungsoberfläche und API haben getrennte Ports.

Zusätzliche API-Kompatibilität

Für lokale Work-/Codex-Aufgaben in der ChatGPT-App und andere Responses-Clients. Verwendet denselben API-Port, Token und die freigegebenen Chat-Profile. Die Chat-Completions-API bleibt verfügbar.

Unterstützt Text, Streaming und Werkzeugaufrufe. Gesprächskontext muss vollständig mitgesendet werden. Keine gespeicherten Antworten, WebSocket-Fortsetzung oder gehosteten OpenAI-Werkzeuge. Umschalten ist ohne Modell-Neustart möglich; laufende Anfragen werden beendet.

Am Endpunkt angebotene Profile

Nur explizit aktivierte, ausführbare Profile erscheinen in GET /v1/models. Aktivieren lädt noch kein Modell.

API-Routen

POST /v1/chat/completions · Text und Streaming
POST /v1/responses · optional über den Kompatibilitätsschalter
POST /v1/images/generations · Qwen-Image-Rezept, ein Bild als b64_json
POST /v1/audio/speech und POST /v1/audio/transcriptions · noch nicht eingerichtet (501)

Alle Routen nutzen denselben Port und Bearer-Token. Bei Bildaufträgen bestimmt das Profil Auflösung, Schritte, Guidance und Seed. Noch keine Bildbearbeitung oder Vision-Eingaben.

':''}
`; root=view.querySelector('#endpoint-page'); if(settings)for(const action of ['start','stop'])root.querySelector('#endpoint-'+action).onclick=()=>mutate('/'+action,{}); + root.querySelector('#endpoint-responses')?.addEventListener('change',event=>mutate('/config',{responses_compat:event.target.checked})); root.querySelector('#endpoint-port-form')?.addEventListener('submit',event=>{event.preventDefault();mutate('/config',{port:Number(root.querySelector('#endpoint-port').value)});}); } if(pending)return;const id=sequence; @@ -57,7 +58,7 @@ window.EndpointUI=(()=>{ if(!settings){control(s,root);clearTimeout(controlTimer);if(s.video?.state==='switching'||s.worker.state==='loading'||s.state==='stopping')controlTimer=setTimeout(()=>{if(root.isConnected)render(false);},1000);return;} put(root.querySelector('#endpoint-summary'),summary(s)); root.querySelector('#endpoint-start').disabled=s.state!=='stopped';root.querySelector('#endpoint-stop').disabled=s.state!=='running'; - if(settings){const port=root.querySelector('#endpoint-port');if(document.activeElement!==port)port.value=s.port;port.disabled=s.state!=='stopped';root.querySelector('#endpoint-port-save').disabled=s.state!=='stopped'; + if(settings){root.querySelector('#endpoint-responses').checked=!!s.responses_compat;const port=root.querySelector('#endpoint-port');if(document.activeElement!==port)port.value=s.port;port.disabled=s.state!=='stopped';root.querySelector('#endpoint-port-save').disabled=s.state!=='stopped'; root.querySelector('#endpoint-port-help').textContent=s.allowed_ports.length?'Docker-Testinstallation: veröffentlichte Loopback-Ports '+s.allowed_ports.join(', ')+'. Portwechsel nur bei gestopptem Endpunkt. Der SSH-Tunnel muss denselben Port weiterleiten.':'Nativer Dienst: freie Ports zwischen 1024 und 65535, nur bei gestopptem Endpunkt.'; put(root.querySelector('#endpoint-profiles'),s.profiles.map(p=>`
${e(p.name)} · ${e(p.kind)} · ${p.runnable?'ausführbar':e(p.blockers.join(' '))}
`).join('')||'

Noch keine Profile angelegt. Erstelle sie in der jeweiligen Modellkategorie.

'); root.querySelectorAll('[data-enable]').forEach(b=>{const p=s.profiles.find(p=>p.id===b.dataset.enable);b.disabled=!p.runnable&&!p.enabled;b.onclick=()=>mutate('/profile',{id:b.dataset.enable,enabled:b.dataset.value==='true'});}); diff --git a/endpoint.py b/endpoint.py index ba8f623..ef7ed03 100644 --- a/endpoint.py +++ b/endpoint.py @@ -16,6 +16,7 @@ from api_compat import normalize_chat,CompatibilityError from profiles import generation_parameters from inference import InferenceError from stt import read_upload +from responses_compat import translate as translate_responses,ResponsesError class APIError(ValueError): def __init__(self,message,status=400,code='invalid_request_error'): @@ -44,7 +45,7 @@ class Endpoint: self.root=Path(root);self.profiles=profiles;self.worker=worker;self.scheduler=scheduler;self.images=images;self.tts=None;self.voxcpm=None;self.embeddings=None;self.stt=None;self.music=None;self.video=None;self.credentials=credentials self.management_port=management_port;self.lock=threading.RLock();self.http=None;self.thread=None;self.state='stopped';self.error=None;self.inflight=0 self.allowed_ports=[int(p) for p in os.environ.get('DECK_API_PORTS','').split(',') if p] - self.config=dict(port=self.allowed_ports[0] if self.allowed_ports else 8120,enabled_profiles=[],autostart=False) + self.config=dict(port=self.allowed_ports[0] if self.allowed_ports else 8120,enabled_profiles=[],autostart=False,responses_compat=False) path=self.root/'endpoint.json' if path.exists():self.config.update(json.loads(path.read_text())) image_ids={p['id'] for p in self.profiles.status()['profiles'] if p['kind']=='image'} @@ -67,8 +68,12 @@ class Endpoint: # Video status can call back into endpoint.rows(); never hold our lock # while acquiring another service's lock. Concurrent GUI requests otherwise deadlock. video_status=self.video.status() if self.video else None - with self.lock:return dict(video=video_status,state=self.state,reachable=bool(self.thread and self.thread.is_alive() and self.state=='running'),port=self.config['port'],bind=os.environ.get('DECK_API_BIND','127.0.0.1'),base_url=f"http://127.0.0.1:{self.config['port']}/v1",allowed_ports=self.allowed_ports,error=self.error,counts=counts,worker=worker,scheduler=scheduler_status,profiles=[dict(id=p['id'],name=p['name'],kind=p['kind'],enabled=p['enabled'],runnable=p['runnable'],blockers=p['blockers']) for p in rows],active_requests=self.inflight) + with self.lock:return dict(responses_compat=bool(self.config.get('responses_compat',False)),video=video_status,state=self.state,reachable=bool(self.thread and self.thread.is_alive() and self.state=='running'),port=self.config['port'],bind=os.environ.get('DECK_API_BIND','127.0.0.1'),base_url=f"http://127.0.0.1:{self.config['port']}/v1",allowed_ports=self.allowed_ports,error=self.error,counts=counts,worker=worker,scheduler=scheduler_status,profiles=[dict(id=p['id'],name=p['name'],kind=p['kind'],enabled=p['enabled'],runnable=p['runnable'],blockers=p['blockers']) for p in rows],active_requests=self.inflight) def configure(self,data): + if set(data)=={'responses_compat'}: + if type(data['responses_compat']) is not bool:raise ValueError('Responses-Kompatibilität muss an oder aus sein.') + with self.lock:self.config['responses_compat']=data['responses_compat'];self.persist() + return self.status() if set(data)!={'port'} or type(data['port']) is not int or not 1024<=data['port']<=65535:raise ValueError('Port zwischen 1024 und 65535 erforderlich.') port=data['port'] with self.lock: @@ -249,7 +254,10 @@ class APIHandler(BaseHTTPRequestHandler): return if self.command=='GET' and self.path=='/v1/capabilities': from api_compat import capabilities - return self.send(capabilities()) + value=capabilities();enabled=bool(ep.config.get('responses_compat',False)) + value['responses']=dict(enabled=enabled,route='/v1/responses',stateless=True,websockets=False,stored_responses=False,tools=['function','custom'],output_formats=['text']) + if enabled:value['unsupported_routes']=[r for r in value['unsupported_routes'] if r!='/v1/responses'] + return self.send(value) model_routes={'/v1/embeddings/models':'embeddings','/v1/models':'chat','/v1/images/models':'image','/v1/audio/speech/models':'audio','/v1/audio/transcriptions/models':'stt','/v1/audio/music/models':'music'} if self.command=='GET' and self.path in model_routes: listing=ep.model_list(model_routes[self.path]) @@ -271,7 +279,8 @@ class APIHandler(BaseHTTPRequestHandler): fields['n']=int(fields.get('n','1')) return self.image(ep,fields,images) except ValueError as exc:raise APIError(str(exc)) from None - if self.path not in ('/v1/embeddings','/v1/chat/completions','/v1/images/generations','/v1/audio/speech','/v1/audio/music'):raise APIError('Route nicht implementiert.',404) + if self.path=='/v1/responses' and not ep.config.get('responses_compat',False):raise APIError('Responses-Kompatibilität ist deaktiviert. Unter API-Einstellungen einschalten.',404,'responses_disabled') + if self.path not in ('/v1/responses','/v1/embeddings','/v1/chat/completions','/v1/images/generations','/v1/audio/speech','/v1/audio/music'):raise APIError('Route nicht implementiert.',404) if self.headers.get('Transfer-Encoding'):raise APIError('Chunked Upload wird nicht unterstützt.') try:length=int(self.headers.get('Content-Length','0')) except ValueError:raise APIError('Ungültige Content-Length.') from None @@ -279,6 +288,10 @@ class APIHandler(BaseHTTPRequestHandler): try:data=json.loads(self.rfile.read(length),parse_constant=lambda _:(_ for _ in ()).throw(ValueError())) except (ValueError,UnicodeError):raise APIError('Ungültiges JSON.') from None if not isinstance(data,dict):raise APIError('JSON-Objekt erforderlich.') + if self.path=='/v1/responses': + try:chat,converter=translate_responses(data) + except ResponsesError as exc:raise APIError(str(exc)) from None + return self.chat(ep,chat,converter) if self.path=='/v1/embeddings':return self.embedding(ep,data) if self.path=='/v1/chat/completions':return self.chat(ep,data) if self.path=='/v1/audio/music':return self.music_generation(ep,data) @@ -359,7 +372,7 @@ class APIHandler(BaseHTTPRequestHandler): except (ValueError,OSError):time.sleep(.5);continue self.sent=True;self.send_response(200);self.send_header('Content-Type','audio/wav');self.send_header('Content-Length',str(len(body)));self.send_header('Cache-Control','no-store');self.end_headers();self.wfile.write(body);return ep.music.stop();raise APIError('Musik-Zeitlimit überschritten.',504) - def chat(self,ep,data): + def chat(self,ep,data,converter=None): try:data,self.compatibility=normalize_chat(data) except CompatibilityError as exc:raise APIError(str(exc)) from None if type(data.get('stream',False)) is not bool:raise APIError('stream muss true oder false sein.') @@ -399,15 +412,27 @@ class APIHandler(BaseHTTPRequestHandler): if not data.get('stream'): raw=response.read(16*1024*1024+1) if len(raw)>16*1024*1024:raise InferenceError('Modellantwort überschreitet 16 MiB.') - return self.send(json.loads(raw)) + value=json.loads(raw) + if converter: + try:value=converter.complete(value) + except (ResponsesError,ValueError,KeyError,TypeError):raise APIError('Modellantwort nicht Responses-kompatibel.',502,'upstream_response_error') from None + return self.send(value) self.sent=True;self.connection.settimeout(30) self.send_response(200);self.compatibility_headers();self.send_header('Content-Type','text/event-stream');self.send_header('Cache-Control','no-store');self.send_header('Connection','close');self.end_headers() + if converter:self.wfile.write(converter.start());self.wfile.flush() deadline=time.monotonic()+600 - while time.monotonic()