The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): an image rejection strips the request, never the session history
rodricksz4h51ef306f68d5f
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 5b5542bb8e3..11d16aba21c 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -2403,6 +2403,9 @@ def init_agent(agent.request_overrides = dict(request_overrides or {})agent.prefill_messages = prefill_messages or [] # Prefilled conversation turnsagent._force_ascii_payload = False+ # (provider, model) that rejected image content this session; build_api_request strips images+ # from requests to that model only, so history keeps them for any model that can see.+ agent._image_rejecting_model = None_init_prompt_cache_config(agent)_init_turn_state(agent, run_budget_seconds)diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex cd9af163fbf..59a2f26045f 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -400,6 +400,21 @@ _IMAGE_REJECTION_PHRASES = ()+def strip_images_for_rejecting_model(agent: Any, api_messages: Any) -> bool:+ """Send-path image strip for a model that rejected image content (see turn_recovery).++ Runs on the per-call ``api_messages`` copy in Hermes's own message format, BEFORE the+ provider-specific conversion: the part types this stripper knows are that format's, and a+ converted payload (Bedrock Converse ``{"image": ...}`` blocks carry no ``type``) would slip+ past it. History is never touched. Keyed on the rejecting (provider, model), so a model+ that accepts images gets them again.+ """+ rejecting = getattr(agent, "_image_rejecting_model", None)+ if rejecting is None or rejecting != (getattr(agent, "provider", None), getattr(agent, "model", None)):+ return False+ return isinstance(api_messages, list) and _strip_images_from_messages(api_messages)++def _looks_like_image_content_rejection(error_body: str) -> bool:"""Return True when a provider error says image/multimodal input is unsupported."""body = str(error_body or "").lower()@@ -413,6 +428,7 @@ __all__ = ["_escape_invalid_chars_in_json_strings", "_repair_tool_call_arguments","_strip_non_ascii", "_sanitize_messages_non_ascii", "_sanitize_tools_non_ascii","_strip_images_from_messages", "_sanitize_structure_non_ascii", "sanitize_outbound_kwargs",+ "strip_images_for_rejecting_model",# call_id policy owners"deterministic_call_id", "coalesce_tool_call_id", "tool_call_id_variants","tool_result_id_variants", "uniquify_tool_call_ids",diff --git a/agent/turn_api_request.py b/agent/turn_api_request.pyindex f218023921f..e1e872c56ba 100644--- a/agent/turn_api_request.py+++ b/agent/turn_api_request.py@@ -114,6 +114,9 @@ def build_api_request(tools_for_api=tools_for_api,))+ # A model that rejected image content gets text only; history keeps the images.+ from agent.message_sanitization import strip_images_for_rejecting_model+ strip_images_for_rejecting_model(agent, api_messages)if tools_for_api == agent.tools:api_kwargs = agent._build_api_kwargs(api_messages)else:diff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex 6d89c588c69..b7c7e31d42b 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -246,15 +246,18 @@ def recover_before_classification(_status_ok = _err_status is None or (400 <= int(_err_status) < 500)if getattr(agent, "_vision_supported", True) and _looks_like_image_content_rejection(_err_body) and _status_ok:agent._vision_supported = False- _imgs_removed = _strip_images_from_messages(messages)- if _imgs_removed:- agent._db_flush_scan_prefix = None+ # Send-path only. A rejection says what THIS model accepts, not what the conversation+ # holds: stripping ``messages`` (canonical history) and forcing a flush deleted every+ # image — and every image-only message — from state.db for good, so a later switch to a+ # vision model found them gone. Same failure as the ASCII strip in #117802. Record the+ # model; build_api_request strips images from each request to it instead.+ agent._image_rejecting_model = (getattr(agent, "provider", None), getattr(agent, "model", None))if isinstance(api_messages, list):_strip_images_from_messages(api_messages)_vlines(agent,- "⚠️ Server rejected image content — switching to text-only mode for this session"- + (". Stripped images from history and retrying." if _imgs_removed else "."),+ "⚠️ Server rejected image content — sending text only to this model; "+ "images stay in the session history.",)return True, active_system_promptdiff --git a/tests/agent/test_image_rejection_fallback.py b/tests/agent/test_image_rejection_fallback.pyindex 98eacc91d29..40217ea5475 100644--- a/tests/agent/test_image_rejection_fallback.py+++ b/tests/agent/test_image_rejection_fallback.py@@ -297,3 +297,85 @@ class TestStripImagesDropsStaleApiContent:assert msgs[0]["api_content"] == "no images here<injected ctx>"assert "api_content" not in msgs[1]+++class TestRejectionNeverReachesPersistedHistory:+ """A rejection says what the CURRENT model accepts, not what the conversation holds.++ The recovery used to strip images from the canonical ``messages`` and force a full flush,+ which deleted every image — and every image-only message — from state.db for good; a later+ switch to a vision model found them gone. Same failure class as the ASCII strip in #117802.+ The strip now happens on the send path only.+ """++ class _Err(Exception):+ status_code = 400+ body = "This model does not support images."++ @staticmethod+ def _agent(provider="text-only-provider", model="text-model"):+ from types import SimpleNamespace++ return SimpleNamespace(+ provider=provider, model=model, _vision_supported=True, _force_ascii_payload=False,+ _image_rejecting_model=None, _db_flush_scan_prefix=7, log_prefix="",+ _vprint=lambda *a, **k: None,+ )++ @staticmethod+ def _history():+ return [+ {"role": "user", "content": [+ {"type": "text", "text": "what is in this?"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},+ ]},+ {"role": "user", "content": [+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,BBBB"}},+ ]},+ ]++ def _recover(self, agent, messages, api_messages):+ from agent.turn_recovery import recover_before_classification++ return recover_before_classification(+ agent, self._Err(), messages=messages, api_messages=api_messages,+ api_kwargs={}, active_system_prompt="sys",+ )++ def test_canonical_history_keeps_its_images(self):+ import copy++ agent, history = self._agent(), self._history()+ before = copy.deepcopy(history)+ wire = copy.deepcopy(history)++ retry, _ = self._recover(agent, history, wire)++ assert retry is True+ assert history == before, "the recovery rewrote persisted history"+ assert agent._db_flush_scan_prefix == 7, "the recovery forced a history rewrite"+ # The in-flight request still goes out text-only.+ assert "image_url" not in str(wire)++ def test_later_requests_to_the_same_model_stay_text_only(self):+ """build_api_request strips each attempt's copy — in Hermes's own message format, before+ provider conversion, so every provider shape (incl. Bedrock's type-less blocks) is covered."""+ from agent.message_sanitization import strip_images_for_rejecting_model++ agent = self._agent()+ self._recover(agent, self._history(), [])++ api_messages = self._history()+ assert strip_images_for_rejecting_model(agent, api_messages) is True+ assert "image_url" not in str(api_messages)++ def test_a_model_that_accepts_images_gets_them_again(self):+ from agent.message_sanitization import strip_images_for_rejecting_model++ agent = self._agent()+ self._recover(agent, self._history(), [])++ agent.provider, agent.model = "vision-provider", "vision-model"+ api_messages = self._history()+ assert strip_images_for_rejecting_model(agent, api_messages) is False+ assert str(api_messages).count("data:image/png") == 2