Add switchable stateless Responses API compatibility
This commit is contained in:
1 parent
a908313c8f
commit
650eb398c6
11 files changed
+376
-18
No files matched your search
@@ -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 = "<enabled Athena API ID>"
|
||||
model_provider = "athena"
|
||||
web_search = "disabled"
|
||||
|
||||
[features]
|
||||
enable_request_compression = false
|
||||
|
||||
[model_providers.athena]
|
||||
name = "Athena Deck"
|
||||
base_url = "http://<Athena address>: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`.
|
||||
@@ -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.')
|
||||
|
||||
+1
-1
@@ -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/
|
||||
|
||||
@@ -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/
|
||||
|
||||
+1
-1
@@ -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):
|
||||
|
||||
+3
-2
@@ -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=`<section id="endpoint-page" data-settings="${settings}"><div class="kicker">${settings?'EINSTELLUNGEN / API':'ATHENA DECK / ROUTER'}</div><h1>${settings?'Endpunkt':'Steuerung'}</h1>${settings?'<p>API-Port und freigegebene Profile verwalten.</p><div class="card-actions"><button id="endpoint-start">Endpunkt starten</button><button class="secondary" id="endpoint-stop">Endpunkt stoppen</button></div>':'<p>Betriebsart wählen und starten.</p><div id="control-modes"></div>'}<p id="endpoint-message" role="status"></p><div id="video-mode-panel"></div><div id="endpoint-summary"></div>${settings?'<section class="card"><h2>Lokaler API-Port</h2><form id="endpoint-port-form"><label>Port<input id="endpoint-port" name="port" type="number" required min="1024" max="65535"></label><button id="endpoint-port-save">Port speichern</button></form><p id="endpoint-port-help"></p><p>Der Zugriff verwendet den API-Token aus <a class="link" href="#access">Zugang & API-Token</a>. Verwaltungsoberfläche und API haben getrennte Ports.</p></section><section class="card"><h2>Am Endpunkt angebotene Profile</h2><p>Nur explizit aktivierte, ausführbare Profile erscheinen in <code>GET /v1/models</code>. Aktivieren lädt noch kein Modell.</p><div id="endpoint-profiles"></div></section><section class="card"><h2>API-Routen</h2><p><code>POST /v1/chat/completions</code> · Text und Streaming<br><code>POST /v1/images/generations</code> · Qwen-Image-Rezept, ein Bild als b64_json<br><code>POST /v1/audio/speech</code> und <code>POST /v1/audio/transcriptions</code> · noch nicht eingerichtet (501)</p><p>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.</p></section>':''}</section>`;
|
||||
sequence++;clearTimeout(controlTimer);selectedMode=null;view.innerHTML=`<section id="endpoint-page" data-settings="${settings}"><div class="kicker">${settings?'EINSTELLUNGEN / API':'ATHENA DECK / ROUTER'}</div><h1>${settings?'Endpunkt':'Steuerung'}</h1>${settings?'<p>API-Port und freigegebene Profile verwalten.</p><div class="card-actions"><button id="endpoint-start">Endpunkt starten</button><button class="secondary" id="endpoint-stop">Endpunkt stoppen</button></div>':'<p>Betriebsart wählen und starten.</p><div id="control-modes"></div>'}<p id="endpoint-message" role="status"></p><div id="video-mode-panel"></div><div id="endpoint-summary"></div>${settings?'<section class="card"><h2>Lokaler API-Port</h2><form id="endpoint-port-form"><label>Port<input id="endpoint-port" name="port" type="number" required min="1024" max="65535"></label><button id="endpoint-port-save">Port speichern</button></form><p id="endpoint-port-help"></p><p>Der Zugriff verwendet den API-Token aus <a class="link" href="#access">Zugang & API-Token</a>. Verwaltungsoberfläche und API haben getrennte Ports.</p></section><section class="card"><h2>Zusätzliche API-Kompatibilität</h2><label><input id="endpoint-responses" type="checkbox"> Responses-API aktivieren</label><p>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.</p><p>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.</p></section><section class="card"><h2>Am Endpunkt angebotene Profile</h2><p>Nur explizit aktivierte, ausführbare Profile erscheinen in <code>GET /v1/models</code>. Aktivieren lädt noch kein Modell.</p><div id="endpoint-profiles"></div></section><section class="card"><h2>API-Routen</h2><p><code>POST /v1/chat/completions</code> · Text und Streaming<br><code>POST /v1/responses</code> · optional über den Kompatibilitätsschalter<br><code>POST /v1/images/generations</code> · Qwen-Image-Rezept, ein Bild als b64_json<br><code>POST /v1/audio/speech</code> und <code>POST /v1/audio/transcriptions</code> · noch nicht eingerichtet (501)</p><p>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.</p></section>':''}</section>`;
|
||||
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=>`<div class="note"><strong>${e(p.name)}</strong> · ${e(p.kind)} · ${p.runnable?'ausführbar':e(p.blockers.join(' '))}<br><button class="secondary" data-enable="${e(p.id)}" data-value="${!p.enabled}" ${!p.runnable&&!p.enabled?'disabled':''}>${p.enabled?'Am Endpunkt deaktivieren':'Am Endpunkt aktivieren'}</button></div>`).join('')||'<p>Noch keine Profile angelegt. Erstelle sie in der jeweiligen Modellkategorie.</p>');
|
||||
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'});});
|
||||
|
||||
+36
-11
@@ -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()<deadline:
|
||||
chunk=response.read1(8192)
|
||||
if not chunk:return
|
||||
self.wfile.write(chunk);self.wfile.flush()
|
||||
raise InferenceError('Zeitlimit der Streaming-Antwort überschritten.')
|
||||
try:
|
||||
while time.monotonic()<deadline:
|
||||
chunk=response.read1(8192)
|
||||
if not chunk:
|
||||
if converter:self.wfile.write(converter.finish());self.wfile.flush()
|
||||
return
|
||||
self.wfile.write(converter.feed(chunk) if converter else chunk);self.wfile.flush()
|
||||
raise InferenceError('Zeitlimit der Streaming-Antwort überschritten.')
|
||||
except (ResponsesError,ValueError,KeyError,TypeError,OSError,InferenceError):
|
||||
if converter:
|
||||
self.wfile.write(converter.failure());self.wfile.flush();return
|
||||
raise
|
||||
finally:conn.close()
|
||||
def image(self,ep,data,reference_images=None):
|
||||
if set(data)-{'model','prompt','n','size','response_format','user'}:raise APIError('Nicht unterstützte Bildparameter. Schritte/Guidance/Seed stehen im Profil.')
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""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)
|
||||
@@ -45,12 +45,16 @@ class RestoreTests(unittest.TestCase):
|
||||
time.sleep(.05)
|
||||
self.fail('restore did not finish')
|
||||
def test_export_excludes_weights_media_logs_and_includes_settings_and_history(self):
|
||||
self.server.endpoint.configure({'responses_compat':True})
|
||||
ident=self.model();self.profile(ident)
|
||||
for folder in ('image-tests','tts-tests','llama-worker'):
|
||||
p=self.root/folder;p.mkdir(exist_ok=True);(p/'private.log').write_text('PRIVATE-CHAT-LOG')
|
||||
doc=open_backup(self.server.backup.export('backup secure password'),'backup secure password')
|
||||
self.assertNotIn('PRIVATE-CHAT-LOG',json.dumps(doc));self.assertNotIn('model-weights-not-in-backup',json.dumps(doc));self.assertIn('history',doc);validate(doc)
|
||||
self.assertEqual(doc['models'][0]['id'],ident);self.assertEqual(len(doc['settings']['profiles.json']),1)
|
||||
self.assertTrue(doc['settings']['endpoint.json']['responses_compat'])
|
||||
bad=copy.deepcopy(doc);bad['settings']['endpoint.json']['responses_compat']='true'
|
||||
with self.assertRaises(ValueError):validate(bad)
|
||||
def test_profile_presets_roundtrip_and_invalid_reference_rejected(self):
|
||||
ident=self.model();self.profile(ident);p=self.server.profiles.rows[0]
|
||||
saved=self.server.profiles.preset(dict(id=p['id'],revision=p['revision'],action='save',name='Vor dem Test'))
|
||||
|
||||
+26
-1
@@ -28,7 +28,7 @@ class Upstream(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
w=self.server.worker;data=json.loads(self.rfile.read(int(self.headers['Content-Length'])));w.requests.append(data)
|
||||
if data.get('stream'):
|
||||
self.send_response(200);self.send_header('Content-Type','text/event-stream');self.end_headers();self.wfile.write(b'data: {"choices":[]}\n\n');self.wfile.flush();w.block.wait(3);self.wfile.write(b'data: [DONE]\n\n')
|
||||
self.send_response(200);self.send_header('Content-Type','text/event-stream');self.end_headers();self.wfile.write(getattr(w,'stream_frame',b'data: {"choices":[]}\n\n'));self.wfile.flush();w.block.wait(3);self.wfile.write(b'data: [DONE]\n\n')
|
||||
else:
|
||||
body=json.dumps(dict(id='test',model=data['model'],choices=[{'message':{'role':'assistant','content':'synthetic'}}])).encode();self.send_response(200);self.send_header('Content-Length',str(len(body)));self.end_headers();self.wfile.write(body)
|
||||
|
||||
@@ -70,6 +70,31 @@ class EndpointTests(unittest.TestCase):
|
||||
for name in ['qwen-medium','Qwen Medium','Old Name']:
|
||||
self.assertEqual(self.ep.find_profile(name,'chat')['id'],'alpha')
|
||||
|
||||
def test_responses_toggle_auth_and_existing_route(self):
|
||||
self.enable('alpha')
|
||||
self.assertEqual(self.request('/v1/responses',dict(model='alpha',input='hi'))[0],404)
|
||||
self.ep.configure({'responses_compat':True})
|
||||
self.assertTrue(self.ep.status()['responses_compat'])
|
||||
self.assertEqual(self.request('/v1/responses',dict(model='alpha',input='hi'),token='bad')[0],401)
|
||||
status,result=self.request('/v1/responses',dict(model='alpha',input=[dict(role='user',content='hi'),dict(role='developer',content='late instruction')]))
|
||||
self.assertEqual(status,200);self.assertEqual(result['object'],'response');self.assertEqual(result['output'][0]['content'][0]['text'],'synthetic')
|
||||
self.assertEqual(self.worker.requests[-1]['messages'][0],dict(role='system',content='late instruction'))
|
||||
self.assertNotIn('/v1/responses',self.request('/v1/capabilities')[1]['unsupported_routes'])
|
||||
saved=json.loads((self.ep.root/'endpoint.json').read_text());self.assertTrue(saved['responses_compat'])
|
||||
self.ep.configure({'responses_compat':False})
|
||||
self.assertEqual(self.request('/v1/responses',dict(model='alpha',input='hi'))[0],404)
|
||||
self.assertEqual(self.request('/v1/chat/completions',dict(model='alpha',messages=[dict(role='user',content='hi')]))[0],200)
|
||||
with self.assertRaises(ValueError):self.ep.configure({'responses_compat':'true'})
|
||||
|
||||
def test_responses_successful_stream_and_failed_partial_stream(self):
|
||||
self.enable('alpha');self.ep.configure({'responses_compat':True})
|
||||
self.worker.stream_frame=b'data: {"choices":[{"delta":{"content":"hello"},"finish_reason":"stop"}]}\n\n'
|
||||
status,body=self.request('/v1/responses',dict(model='alpha',input='hi',stream=True))
|
||||
self.assertEqual(status,200);self.assertIn(b'response.output_text.delta',body);self.assertIn(b'response.completed',body)
|
||||
self.worker.stream_frame=b'data: {"choices":[{"delta":{"content":"partial"}}]}\n\n'
|
||||
_,body=self.request('/v1/responses',dict(model='alpha',input='hi',stream=True))
|
||||
self.assertIn(b'response.failed',body);self.assertNotIn(b'response.completed',body)
|
||||
|
||||
def test_discovery_reports_profile_context_without_loading(self):
|
||||
self.rows[0]['parameters'].update(context=160000,slots=2)
|
||||
self.rows[0]['model']={'repo':'Qwen/Qwen3.8-27B'}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import json
|
||||
import unittest
|
||||
from responses_compat import translate,ResponsesError
|
||||
|
||||
class ResponsesTests(unittest.TestCase):
|
||||
def test_instructions_tools_and_history_preserved_without_token_cap(self):
|
||||
body=dict(model='qwen',instructions='base',tools=[dict(type='namespace',name='functions',tools=[dict(type='custom',name='patch'),dict(type='function',name='read')])],input=[dict(role='user',content='hello'),dict(role='developer',content=[dict(type='input_text',text='new instruction')]),dict(type='custom_tool_call',namespace='functions',name='patch',call_id='c1',input='line1\nline2'),dict(type='custom_tool_call_output',call_id='c1',output='ok')])
|
||||
chat,_=translate(body)
|
||||
self.assertEqual(chat['messages'][0],dict(role='system',content='base\n\nnew instruction'))
|
||||
self.assertEqual(chat['messages'][-1]['tool_call_id'],'c1')
|
||||
self.assertEqual(json.loads(chat['messages'][-2]['tool_calls'][0]['function']['arguments']),{'input':'line1\nline2'})
|
||||
self.assertNotIn('max_tokens',chat)
|
||||
self.assertEqual(translate(dict(body,max_output_tokens=30000))[0]['max_tokens'],30000)
|
||||
def test_unsupported_semantics_rejected(self):
|
||||
for addition in [dict(previous_response_id='r1'),dict(store=True),dict(tools=[dict(type='web_search')]),dict(text=dict(format=dict(type='json_schema'))),dict(truncation='auto')]:
|
||||
with self.subTest(addition=addition),self.assertRaises(ResponsesError):translate(dict(model='q',input='hi',**addition))
|
||||
def test_incremental_utf8_stream_and_incomplete(self):
|
||||
_,c=translate(dict(model='q',input='hi'))
|
||||
data=('data: '+json.dumps(dict(choices=[dict(delta=dict(content='Grüße'),finish_reason=None)]),ensure_ascii=False)+'\n\n').encode()
|
||||
out=b''
|
||||
for b in data:out+=c.feed(bytes([b]))
|
||||
self.assertIn(b'response.output_text.delta',out)
|
||||
with self.assertRaises(ResponsesError):c.finish()
|
||||
c.feed(b'data: {"choices":[{"delta":{},"finish_reason":"length"}]}\n\ndata: [DONE]\n\n')
|
||||
self.assertIn(b'response.incomplete',c.finish());self.assertEqual(c.response['incomplete_details']['reason'],'max_output_tokens')
|
||||
def test_namespaced_custom_output_can_be_replayed(self):
|
||||
body=dict(model='q',tools=[dict(type='namespace',name='functions',tools=[dict(type='custom',name='patch')])],input='hi')
|
||||
_,c=translate(body)
|
||||
response=c.complete(dict(choices=[dict(message=dict(tool_calls=[dict(id='c1',function=dict(name='functions__patch',arguments=json.dumps({'input':'patch text'})))]),finish_reason='tool_calls')],usage=dict(prompt_tokens=4,completion_tokens=3,total_tokens=7)))
|
||||
call=response['output'][0];self.assertEqual(call['type'],'custom_tool_call');self.assertEqual(call['namespace'],'functions');self.assertEqual(call['input'],'patch text')
|
||||
chat,_=translate(dict(body,input=[call,dict(type='custom_tool_call_output',call_id='c1',output='done')]))
|
||||
self.assertEqual(chat['messages'][-1]['role'],'tool');self.assertEqual(chat['messages'][-1]['tool_call_id'],'c1')
|
||||
self.assertEqual(response['usage']['total_tokens'],7)
|
||||
def test_malformed_or_unadvertised_tool_never_completes(self):
|
||||
_,c=translate(dict(model='q',input='hi'))
|
||||
value={'choices':[{'message':{'tool_calls':[{'id':'c1','function':{'name':'unknown','arguments':'{}'}}]}}]}
|
||||
with self.assertRaises(ResponsesError):c.complete(value)
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user