Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(brain): serve Responses-API-only OpenAI models instead of a fake network apology
rubenluetke10-beep943d1837a8e1
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 2ae1b8f0d6..89ad1aa688 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -11589,6 +11589,11 @@ def _is_invalid_model_exc(msg: str) -> bool:"model_not_found", "model not found", "model does not exist","unknown model", "invalid model", "invalid_model","not a valid model", "unsupported model",+ # OpenAI's 404 for a Responses-API-only model called over+ # Chat-Completions ("This is not a chat model and thus not supported+ # in the v1/chat/completions endpoint"). Live 2026-08-06: spoken as+ # "network or provider issue", which sent the user hunting API keys.+ "not a chat model",))diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.pyindex bc0605d81d..267807b1ea 100644--- a/jarvis/plugins/brain/_openai_base.py+++ b/jarvis/plugins/brain/_openai_base.py@@ -242,6 +242,237 @@ def _tools_openai_format(return out+# ---------------------------------------------------------------------------+# Responses-API compatibility (rejection-driven, like the param retries below)+# ---------------------------------------------------------------------------++# OpenAI serves its "pro" deep-reasoning class (gpt-5.5-pro, ...) ONLY via the+# Responses API: a Chat-Completions call returns 404 "This is not a chat+# model...". Live 2026-08-06 20:19: the screen-context vision turn crossed+# families onto openai(gpt-5.5-pro), took that 404, and the user heard the+# dishonest "network or provider issue" apology. Detection is by the server's+# EXPLICIT rejection, never by model-name pinning (AP-21), and the verdict is+# cached per (base_url, model) so later turns skip the failed round-trip.+_RESPONSES_ONLY_MARKERS = (+ "not a chat model",+ "not supported in the v1/chat/completions",+ "only supported in v1/responses",+ "use the responses api",+)++#: (base_url, model) pairs the server has declared Responses-only.+_RESPONSES_ONLY_CACHE: set[tuple[str, str]] = set()+++def _is_responses_only_rejection(exc: Exception) -> bool:+ """Whether the server explicitly refused the model on Chat-Completions."""+ message = str(exc).lower()+ return any(marker in message for marker in _RESPONSES_ONLY_MARKERS)+++def _client_supports_responses(client: Any) -> bool:+ """Whether the installed SDK exposes the Responses API at all."""+ return callable(getattr(getattr(client, "responses", None), "create", None))+++def _chat_messages_to_responses_input(+ messages: list[dict[str, Any]],+) -> tuple[str | None, list[dict[str, Any]]]:+ """Translate an already-built Chat-Completions array to Responses input.++ system → ``instructions``; user text/image blocks → ``input_text`` /+ ``input_image``; assistant ``tool_calls`` → ``function_call`` items; tool+ results → ``function_call_output`` items. Translating the FINISHED chat+ array (not the BrainMessages) keeps one message builder as the single+ source of truth for history reconstruction and name sanitizing.+ """+ instruction_parts: list[str] = []+ items: list[dict[str, Any]] = []+ for m in messages:+ role = m.get("role")+ content = m.get("content")+ if role == "system":+ if isinstance(content, str) and content:+ instruction_parts.append(content)+ continue+ if role == "tool":+ items.append({+ "type": "function_call_output",+ "call_id": m.get("tool_call_id") or "",+ "output": (+ content+ if isinstance(content, str)+ else json.dumps(content, default=str)+ ),+ })+ continue+ if role == "assistant":+ if isinstance(content, str) and content:+ items.append({+ "role": "assistant",+ "content": [{"type": "output_text", "text": content}],+ })+ for tc in m.get("tool_calls") or ():+ fn = tc.get("function") or {}+ items.append({+ "type": "function_call",+ "call_id": tc.get("id") or "",+ "name": fn.get("name") or "",+ "arguments": fn.get("arguments") or "{}",+ })+ continue+ # user+ if isinstance(content, list):+ blocks: list[dict[str, Any]] = []+ for block in content:+ if not isinstance(block, dict):+ continue+ btype = block.get("type")+ if btype == "text":+ blocks.append({+ "type": "input_text", "text": block.get("text", "")+ })+ elif btype == "image_url":+ url = (block.get("image_url") or {}).get("url") or ""+ if url:+ blocks.append({"type": "input_image", "image_url": url})+ items.append({"role": "user", "content": blocks})+ else:+ items.append({+ "role": "user",+ "content": [{+ "type": "input_text",+ "text": (+ content+ if isinstance(content, str)+ else json.dumps(content, default=str)+ ),+ }],+ })+ return ("\n\n".join(instruction_parts) or None), items+++def _tools_responses_format(+ chat_tools: list[dict[str, Any]],+) -> list[dict[str, Any]]:+ """Chat-Completions nested function tools → flat Responses function tools."""+ out: list[dict[str, Any]] = []+ for t in chat_tools:+ fn = t.get("function") or {}+ out.append({+ "type": "function",+ "name": fn.get("name", ""),+ "description": fn.get("description", ""),+ "parameters": fn.get("parameters")+ or {"type": "object", "properties": {}},+ })+ return out+++# Reasoning tokens count against ``max_output_tokens`` on the Responses API,+# and the models that land on this transport reason MANDATORILY. A small+# chat-era budget (the CU tool step sends 256) would be consumed by hidden+# thought before the first visible token, returning an empty "incomplete"+# answer — so the budget is floored here.+_RESPONSES_MIN_OUTPUT_TOKENS = 4096+++def _responses_kwargs_from_chat(chat_kwargs: dict[str, Any]) -> dict[str, Any]:+ """Build ``responses.create`` kwargs from prepared Chat-Completions kwargs.++ Deliberately NOT carried over: ``temperature`` and ``reasoning_effort``+ (the deep-reasoning models this transport exists for reject sampling+ knobs and refuse to switch reasoning off) and ``stream_options`` (usage+ arrives on the terminal ``response.completed`` event instead).+ """+ instructions, input_items = _chat_messages_to_responses_input(+ list(chat_kwargs.get("messages") or ())+ )+ out: dict[str, Any] = {+ "model": chat_kwargs.get("model"),+ "input": input_items,+ "stream": True,+ }+ if instructions:+ out["instructions"] = instructions+ max_out = chat_kwargs.get("max_completion_tokens") or chat_kwargs.get(+ "max_tokens"+ )+ if max_out:+ out["max_output_tokens"] = max(int(max_out), _RESPONSES_MIN_OUTPUT_TOKENS)+ if chat_kwargs.get("tools"):+ out["tools"] = _tools_responses_format(list(chat_kwargs["tools"]))+ return out+++async def _stream_via_responses(+ client: Any,+ chat_kwargs: dict[str, Any],+ reverse_name_map: dict[str, str],+) -> AsyncIterator[BrainDelta]:+ """Stream one turn over the Responses API, emitting the same BrainDeltas.++ Delta parity with the chat path: text deltas while streaming, tool calls+ finalized before the ``finish_reason``, usage last.+ """+ stream = await client.responses.create(+ **_responses_kwargs_from_chat(chat_kwargs)+ )+ tool_calls: list[dict[str, Any]] = []+ usage_payload: dict[str, int] | None = None+ failure: str | None = None+ async for event in stream:+ etype = str(getattr(event, "type", "") or "")+ if etype == "response.output_text.delta":+ delta = getattr(event, "delta", None)+ if delta:+ yield BrainDelta(content=delta)+ elif etype == "response.output_item.done":+ item = getattr(event, "item", None)+ if str(getattr(item, "type", "") or "") == "function_call":+ name = getattr(item, "name", "") or ""+ try:+ parsed = json.loads(getattr(item, "arguments", "") or "{}")+ except json.JSONDecodeError:+ parsed = {}+ tool_calls.append({+ "id": (+ getattr(item, "call_id", None)+ or getattr(item, "id", None)+ or f"call_{len(tool_calls)}"+ ),+ "name": reverse_name_map.get(name, name),+ "input": parsed,+ })+ elif etype in ("response.completed", "response.incomplete"):+ usage = getattr(getattr(event, "response", None), "usage", None)+ if usage is not None:+ usage_payload = {+ "input_tokens": int(getattr(usage, "input_tokens", 0) or 0),+ "output_tokens": int(+ getattr(usage, "output_tokens", 0) or 0+ ),+ }+ details = getattr(usage, "input_tokens_details", None)+ cached = int(getattr(details, "cached_tokens", 0) or 0)+ if cached > 0:+ usage_payload["cache_hit_tokens"] = cached+ elif etype in ("response.failed", "error"):+ err = getattr(getattr(event, "response", None), "error", None)+ if err is None:+ err = getattr(event, "error", None)+ failure = str(+ getattr(err, "message", None) or err or "response failed"+ )+ if failure:+ raise RuntimeError(f"Responses API stream failed: {failure}")+ for tc in tool_calls:+ yield BrainDelta(tool_call=tc)+ yield BrainDelta(finish_reason="tool_calls" if tool_calls else "stop")+ if usage_payload is not None:+ yield BrainDelta(usage=usage_payload)++async def stream_complete(client: Any,model: str,@@ -255,6 +486,10 @@ async def stream_complete(`supports_vision` is passed through to the message builder — when `False`,`BrainMessage.images` are dropped and a WARN is logged.++ Models the server declares Responses-only (404 "not a chat model") are+ transparently served over the Responses API — see+ ``_is_responses_only_rejection``."""# The same map must sanitize both declarations and reconstructed assistant# tool history. Otherwise an MCP name such as ``github/search`` succeeds in@@ -308,12 +543,23 @@ async def stream_complete(# Accumulator for tool-call partials (OpenAI streams per tool_call index)tool_buffer: dict[int, dict[str, Any]] = {}+ # A model the server already declared Responses-only skips the doomed+ # Chat-Completions round-trip for the rest of the process lifetime.+ responses_cache_key = (str(getattr(client, "base_url", "") or ""), model)+ if responses_cache_key in _RESPONSES_ONLY_CACHE and _client_supports_responses(+ client+ ):+ async for delta in _stream_via_responses(client, kwargs, reverse_name_map):+ yield delta+ return+# Belt-and-suspenders for SDK-level kwarg gaps: old SDKs know neither# ``stream_options`` (added ~1.30) nor ``reasoning_effort`` (added ~1.58)# and raise TypeError before any request is sent. Strip exactly the kwarg# the SDK named and retry — an ancient SDK may need both stripped._sdk_optional_kwargs = ("stream_options", "reasoning_effort")stream = None+ use_responses = Falsefor _ in range(len(_sdk_optional_kwargs) + 1):try:stream = await _create_with_token_param_retry(client, kwargs)@@ -331,6 +577,23 @@ async def stream_complete(exc,)kwargs.pop(offender, None)+ except Exception as exc: # noqa: BLE001 — inspect for the transport verdict+ if _is_responses_only_rejection(exc) and _client_supports_responses(+ client+ ):+ _RESPONSES_ONLY_CACHE.add(responses_cache_key)+ log.info(+ "model %s is Responses-API-only per the server's rejection "+ "— switching transport (cached for this endpoint).",+ model,+ )+ use_responses = True+ break+ raise+ if use_responses:+ async for delta in _stream_via_responses(client, kwargs, reverse_name_map):+ yield delta+ returnif stream is None: # pragma: no cover -- loop always breaks or raisesraise RuntimeError("openai stream creation retry loop exhausted")async for chunk in stream:diff --git a/tests/unit/plugins/brain/test_openai_responses_fallback.py b/tests/unit/plugins/brain/test_openai_responses_fallback.pynew file mode 100644index 0000000000..800939dc27--- /dev/null+++ b/tests/unit/plugins/brain/test_openai_responses_fallback.py@@ -0,0 +1,289 @@+"""Responses-API transport fallback for Responses-only OpenAI models.++OpenAI serves its deep-reasoning "pro" class only via the Responses API; a+Chat-Completions call 404s with "This is not a chat model...". Live+2026-08-06 20:19: the screen-context vision turn crossed families onto+openai(gpt-5.5-pro), took exactly that 404, and the user heard the dishonest+"network or provider issue" apology while hunting for broken API keys.++The shared base must (1) switch transports on the server's EXPLICIT rejection+(never on a model-name pin, AP-21), (2) cache the verdict per endpoint+model,+(3) emit the same BrainDelta sequence as the chat path, and (4) classify the+rejection honestly if the transport switch is impossible.+"""+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jarvis.core.protocols import BrainMessage, BrainRequest, ImageBlock+from jarvis.plugins.brain import _openai_base+from jarvis.plugins.brain._openai_base import stream_complete++# The live rejection, verbatim shape (desktop log 2026-08-06 20:19:14).+_NOT_A_CHAT_MODEL_404 = (+ "Error code: 404 - {'error': {'message': 'This is not a chat model and "+ "thus not supported in the v1/chat/completions endpoint. Did you mean to "+ "use v1/completions?', 'type': 'invalid_request_error', 'param': 'model', "+ "'code': None}}"+)++[email protected](autouse=True)+def _fresh_caches(monkeypatch: pytest.MonkeyPatch) -> None:+ """Both process-global memories are isolated per test."""+ monkeypatch.setattr(_openai_base, "_PARAM_ADAPTATION_CACHE", {})+ monkeypatch.setattr(_openai_base, "_RESPONSES_ONLY_CACHE", set())+++class _FakeResponsesStream:+ def __init__(self, events: list[SimpleNamespace]) -> None:+ self._events = list(events)++ def __aiter__(self):+ return self++ async def __anext__(self):+ if not self._events:+ raise StopAsyncIteration+ return self._events.pop(0)+++class _FakeClient:+ """Chat rejects with the live 404; Responses streams a scripted answer."""++ base_url = "https://api.openai.com/v1"++ def __init__(self, events: list[SimpleNamespace]) -> None:+ self.chat_calls: list[dict] = []+ self.responses_calls: list[dict] = []+ self._events = events++ async def _chat_create(**kwargs):+ self.chat_calls.append(kwargs)+ raise RuntimeError(_NOT_A_CHAT_MODEL_404)++ async def _responses_create(**kwargs):+ self.responses_calls.append(kwargs)+ return _FakeResponsesStream(list(self._events))++ chat = SimpleNamespace(completions=SimpleNamespace(create=_chat_create))+ self.chat = chat+ self.responses = SimpleNamespace(create=_responses_create)+++def _text_events() -> list[SimpleNamespace]:+ usage = SimpleNamespace(+ input_tokens=100,+ output_tokens=20,+ input_tokens_details=SimpleNamespace(cached_tokens=0),+ )+ return [+ SimpleNamespace(type="response.output_text.delta", delta="You are on "),+ SimpleNamespace(type="response.output_text.delta", delta="example.com."),+ SimpleNamespace(+ type="response.completed",+ response=SimpleNamespace(usage=usage),+ ),+ ]+++def _vision_request() -> BrainRequest:+ return BrainRequest(+ messages=(+ BrainMessage(role="system", content="You are Jarvis."),+ BrainMessage(+ role="user",+ content="Which domain am I on?",+ images=(ImageBlock(mime="image/png", data_b64="QUJD"),),+ ),+ ),+ max_tokens=256,+ )+++async def _collect(client, model: str, req: BrainRequest) -> list:+ return [d async for d in stream_complete(client, model, req)]+++async def test_not_a_chat_model_404_switches_to_responses_transport() -> None:+ client = _FakeClient(_text_events())+ deltas = await _collect(client, "gpt-5.5-pro", _vision_request())++ text = "".join(d.content for d in deltas if d.content)+ assert text == "You are on example.com."+ assert [d.finish_reason for d in deltas if d.finish_reason] == ["stop"]+ usage = next(d.usage for d in deltas if d.usage)+ assert usage == {"input_tokens": 100, "output_tokens": 20}++ # The failed chat probe ran exactly once, then the Responses call.+ assert len(client.chat_calls) == 1+ assert len(client.responses_calls) == 1++ r_kwargs = client.responses_calls[0]+ assert r_kwargs["model"] == "gpt-5.5-pro"+ assert r_kwargs["instructions"] == "You are Jarvis."+ # Reasoning models spend hidden thought against max_output_tokens; the+ # tiny chat-era budget must be floored or the answer arrives empty.+ assert r_kwargs["max_output_tokens"] >= 4096+ # Sampling and reasoning knobs are deliberately not carried over.+ assert "temperature" not in r_kwargs+ assert "reasoning_effort" not in r_kwargs++ user_item = next(+ i for i in r_kwargs["input"] if i.get("role") == "user"+ )+ kinds = [b["type"] for b in user_item["content"]]+ assert kinds == ["input_text", "input_image"]+ assert user_item["content"][1]["image_url"].startswith("data:image/png;base64,")+++async def test_verdict_is_cached_so_second_turn_skips_the_chat_probe() -> None:+ client = _FakeClient(_text_events())+ await _collect(client, "gpt-5.5-pro", _vision_request())++ client._events = _text_events()+ await _collect(client, "gpt-5.5-pro", _vision_request())++ assert len(client.chat_calls) == 1 # only the first turn paid the probe+ assert len(client.responses_calls) == 2+++async def test_function_call_items_come_back_as_tool_call_deltas() -> None:+ events = [+ SimpleNamespace(+ type="response.output_item.done",+ item=SimpleNamespace(+ type="function_call",+ call_id="call_abc",+ name="jarvis_action",+ arguments='{"utterance": "check the screen"}',+ ),+ ),+ SimpleNamespace(+ type="response.completed",+ response=SimpleNamespace(usage=None),+ ),+ ]+ client = _FakeClient(events)+ req = BrainRequest(+ messages=(BrainMessage(role="user", content="do it"),),+ tools=(+ {+ "name": "jarvis_action",+ "description": "Dispatch an action.",+ "input_schema": {"type": "object", "properties": {}},+ },+ ),+ )+ deltas = await _collect(client, "gpt-5.5-pro", req)++ tool = next(d.tool_call for d in deltas if d.tool_call)+ assert tool == {+ "id": "call_abc",+ "name": "jarvis_action",+ "input": {"utterance": "check the screen"},+ }+ assert [d.finish_reason for d in deltas if d.finish_reason] == ["tool_calls"]++ # Declared tools were translated to the flat Responses shape.+ declared = client.responses_calls[0]["tools"]+ assert declared == [+ {+ "type": "function",+ "name": "jarvis_action",+ "description": "Dispatch an action.",+ "parameters": {"type": "object", "properties": {}},+ }+ ]+++async def test_tool_history_round_trips_as_function_call_items() -> None:+ client = _FakeClient(_text_events())+ req = BrainRequest(+ messages=(+ BrainMessage(role="user", content="open the site"),+ BrainMessage(+ role="assistant",+ content=[+ {+ "type": "tool_use",+ "id": "call_1",+ "name": "jarvis_action",+ "input": {"utterance": "open"},+ }+ ],+ ),+ BrainMessage(role="tool", content="done", tool_call_id="call_1"),+ ),+ )+ await _collect(client, "gpt-5.5-pro", req)++ items = client.responses_calls[0]["input"]+ call_item = next(i for i in items if i.get("type") == "function_call")+ assert call_item["call_id"] == "call_1"+ assert call_item["name"] == "jarvis_action"+ output_item = next(i for i in items if i.get("type") == "function_call_output")+ assert output_item == {+ "type": "function_call_output",+ "call_id": "call_1",+ "output": "done",+ }+++async def test_unrelated_errors_are_never_retried_on_responses() -> None:+ class _PlainFailClient:+ base_url = "https://api.openai.com/v1"++ def __init__(self) -> None:+ async def _chat_create(**kwargs):+ raise RuntimeError("Error code: 500 - upstream exploded")++ self.chat = SimpleNamespace(+ completions=SimpleNamespace(create=_chat_create)+ )+ self.responses = SimpleNamespace(create=None)++ with pytest.raises(RuntimeError, match="upstream exploded"):+ await _collect(+ _PlainFailClient(),+ "gpt-5.5",+ BrainRequest(messages=(BrainMessage(role="user", content="hi"),)),+ )+++async def test_sdk_without_responses_api_reraises_the_honest_404() -> None:+ """An old SDK cannot switch transports — the 404 must surface unchanged++ so the manager's classifier reads it as invalid_model (an honest spoken+ cause), never as a silent no-op (AP-30).+ """++ class _OldSdkClient:+ base_url = "https://api.openai.com/v1"++ def __init__(self) -> None:+ async def _chat_create(**kwargs):+ raise RuntimeError(_NOT_A_CHAT_MODEL_404)++ self.chat = SimpleNamespace(+ completions=SimpleNamespace(create=_chat_create)+ )+ # No .responses attribute at all on old SDKs.++ with pytest.raises(RuntimeError, match="not a chat model"):+ await _collect(+ _OldSdkClient(),+ "gpt-5.5-pro",+ BrainRequest(messages=(BrainMessage(role="user", content="hi"),)),+ )+++def test_manager_classifies_the_live_404_as_invalid_model() -> None:+ from jarvis.brain.manager import _classify_provider_error++ assert (+ _classify_provider_error(_NOT_A_CHAT_MODEL_404, default="call_fail")+ == "invalid_model"+ )