fix(providers): prepare inline image batches and recover Codex transport (#6107)
* fix(codex): prepare image batches and recover WebSocket transport * fix(providers): share image preparation across API adapters
This commit is contained in:
1 parent
fb605ddc7b
commit
3fb9417daf
11 files changed
+703
-14
No files matched your search
@@ -86,6 +86,23 @@ You usually omit `apiBase` for hosted built-in providers such as OpenRouter, Ant
|
||||
|
||||
Use `proxy` when one provider must send HTTP traffic through a proxy without changing process-wide `HTTP_PROXY` / `HTTPS_PROXY`. This is supported for providers that use nanobot's OpenAI-compatible client, including `openai`, `custom`, named custom providers, OpenRouter-style gateways, local OpenAI-compatible servers, and similar registry entries. It is also supported for `openai_codex` and `xai_grok`, including OAuth token exchange/refresh and model requests. Native provider backends such as `anthropic`, `bedrock`, `azure_openai`, and `github_copilot` reject `proxy`; use their endpoint-specific configuration instead.
|
||||
|
||||
## Inline Image Requests
|
||||
|
||||
Before sending a large inline image batch, providers prepare smaller copies while
|
||||
keeping the attachment files intact. This applies to Responses, Chat Completions,
|
||||
Anthropic Messages, and Bedrock Converse requests, including images returned by tools
|
||||
and images in Responses history replay. Preparation first re-encodes at the original
|
||||
dimensions, then reduces each dimension by at most 25% if needed, with JPEG quality
|
||||
at least 65. PNG transparency is preserved. The shared 1 MB image data URL budget is
|
||||
a best-effort transport target; small image blocks, animated images, and remote
|
||||
references keep their original payloads. Gateway logs report image sizes and byte counts.
|
||||
|
||||
Preparation preserves each adapter's model and API capability rules. When automatic
|
||||
Responses compatibility fallback is allowed, switching to Chat Completions retains
|
||||
the images. The shared retry policy can retry a non-transient image request error once
|
||||
without images, using text placeholders that explicitly say the images were not delivered.
|
||||
Responses state containing images is discarded before that text-only retry.
|
||||
|
||||
## Common Provider Patterns
|
||||
|
||||
### OpenRouter Gateway
|
||||
@@ -593,6 +610,11 @@ The WebUI reads the account's Codex model catalog online, including current
|
||||
context-window and reasoning-effort metadata. A small compatible catalog remains
|
||||
available when the service cannot be reached.
|
||||
|
||||
After three WebSocket transport failures without a completed reply, the same
|
||||
authenticated session uses HTTP for subsequent attempts. The existing retry policy
|
||||
controls replay and cancellation. WebSocket logs include request bytes, first-event timing,
|
||||
and close codes; unrecognized close reasons are redacted.
|
||||
|
||||
For an eligible X Premium / Grok subscription:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -22,6 +22,7 @@ from nanobot.providers.base import (
|
||||
resolve_stream_idle_timeout_s,
|
||||
tool_arguments_object_for_replay,
|
||||
)
|
||||
from nanobot.providers.images import prepare_message_images
|
||||
|
||||
_ALNUM = string.ascii_letters + string.digits
|
||||
|
||||
@@ -742,7 +743,7 @@ class AnthropicProvider(LLMProvider):
|
||||
tool_choice: str | dict[str, Any] | None = None,
|
||||
) -> LLMResponse:
|
||||
kwargs = self._build_kwargs(
|
||||
messages, tools, model, max_tokens, temperature,
|
||||
await prepare_message_images(messages), tools, model, max_tokens, temperature,
|
||||
reasoning_effort, tool_choice,
|
||||
)
|
||||
try:
|
||||
@@ -780,7 +781,7 @@ class AnthropicProvider(LLMProvider):
|
||||
on_tool_call_delta: Callable[[dict[str, Any]], Awaitable[None]] | None = None,
|
||||
) -> LLMResponse:
|
||||
kwargs = self._build_kwargs(
|
||||
messages, tools, model, max_tokens, temperature,
|
||||
await prepare_message_images(messages), tools, model, max_tokens, temperature,
|
||||
reasoning_effort, tool_choice,
|
||||
)
|
||||
idle_timeout_s = resolve_stream_idle_timeout_s()
|
||||
|
||||
@@ -20,6 +20,7 @@ from nanobot.providers.base import (
|
||||
resolve_stream_idle_timeout_s,
|
||||
tool_arguments_object_for_replay,
|
||||
)
|
||||
from nanobot.providers.images import prepare_message_images
|
||||
|
||||
_IMAGE_DATA_URL = re.compile(r"^data:image/([a-zA-Z0-9.+-]+);base64,(.*)$", re.DOTALL)
|
||||
_TEXT_BLOCK_TYPES = {"text", "input_text", "output_text"}
|
||||
@@ -742,7 +743,7 @@ class BedrockProvider(LLMProvider):
|
||||
) -> LLMResponse:
|
||||
try:
|
||||
kwargs = self._build_kwargs(
|
||||
messages, tools, model, max_tokens, temperature, reasoning_effort, tool_choice
|
||||
await prepare_message_images(messages), tools, model, max_tokens, temperature, reasoning_effort, tool_choice
|
||||
)
|
||||
response = cast(
|
||||
dict[str, Any],
|
||||
@@ -775,7 +776,7 @@ class BedrockProvider(LLMProvider):
|
||||
|
||||
try:
|
||||
kwargs = self._build_kwargs(
|
||||
messages, tools, model, max_tokens, temperature, reasoning_effort, tool_choice
|
||||
await prepare_message_images(messages), tools, model, max_tokens, temperature, reasoning_effort, tool_choice
|
||||
)
|
||||
response = cast(
|
||||
dict[str, Any],
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Prepare inline image copies within a shared provider request byte budget."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
from collections.abc import Iterator
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from math import ceil
|
||||
from typing import Any, cast
|
||||
|
||||
from loguru import logger
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
# A soft transport target, including base64 expansion, rather than an API size limit.
|
||||
INLINE_IMAGE_BYTE_BUDGET = 1_000_000
|
||||
_SMALL_IMAGE_BYTES = 64_000
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _InlineImage:
|
||||
container: dict[str, Any]
|
||||
key: str
|
||||
detail: object
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return cast(str, self.container[self.key])
|
||||
|
||||
|
||||
def _inline_images(body: dict[str, Any]) -> Iterator[_InlineImage]:
|
||||
items = body.get("input", body.get("messages"))
|
||||
# Responses also accepts a plain-text input string.
|
||||
if not isinstance(items, list):
|
||||
return
|
||||
for item in cast(list[dict[str, Any]], items):
|
||||
content = item.get("output") if item.get("type") == "function_call_output" else item.get("content")
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for block in cast(list[dict[str, Any]], content):
|
||||
container = block
|
||||
key = "image_url"
|
||||
if block.get("type") == "image_url" and isinstance(block.get("image_url"), dict):
|
||||
container = cast(dict[str, Any], block["image_url"])
|
||||
key = "url"
|
||||
elif block.get("type") != "input_image":
|
||||
continue
|
||||
url = container.get(key)
|
||||
if (
|
||||
isinstance(url, str)
|
||||
and url.startswith("data:image/") and ";base64," in url
|
||||
):
|
||||
yield _InlineImage(container, key, container.get("detail"))
|
||||
|
||||
|
||||
@dataclass
|
||||
class _ImageCopy:
|
||||
target: _InlineImage
|
||||
source: Image.Image
|
||||
format: str
|
||||
original_bytes: int
|
||||
sent_bytes: int
|
||||
sent_size: tuple[int, int]
|
||||
|
||||
def encode(self, quality: int, scale: float) -> None:
|
||||
if self.format == "PNG" and scale == 1 and quality != 85:
|
||||
return
|
||||
image = self.source
|
||||
if scale < 1 and self.target.detail != "original":
|
||||
image = image.resize( # pyright: ignore[reportUnknownMemberType]
|
||||
(ceil(image.width * scale), ceil(image.height * scale)),
|
||||
Image.Resampling.LANCZOS,
|
||||
)
|
||||
output = io.BytesIO()
|
||||
image.save(output, format=self.format, quality=quality, optimize=True)
|
||||
raw = output.getvalue()
|
||||
if len(raw) < self.sent_bytes:
|
||||
self.sent_bytes = len(raw)
|
||||
self.sent_size = image.size
|
||||
mime = "image/png" if self.format == "PNG" else "image/jpeg"
|
||||
self.target.container[self.target.key] = f"data:{mime};base64,{base64.b64encode(raw).decode()}"
|
||||
|
||||
|
||||
async def prepare_inline_images(body: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Keep small requests unchanged and prepare large image batches off the event loop."""
|
||||
total_bytes = sum(len(image.url) for image in _inline_images(body))
|
||||
if total_bytes <= INLINE_IMAGE_BYTE_BUDGET:
|
||||
return body
|
||||
return await asyncio.to_thread(_prepare_copies, body, total_bytes)
|
||||
|
||||
|
||||
async def prepare_message_images(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Prepare public image_url messages before provider-specific conversion."""
|
||||
prepared = await prepare_inline_images({"messages": messages})
|
||||
return cast(list[dict[str, Any]], prepared["messages"])
|
||||
|
||||
|
||||
def _prepare_copies(body: dict[str, Any], total_bytes: int) -> dict[str, Any]:
|
||||
prepared = deepcopy(body)
|
||||
blocks = list(_inline_images(prepared))
|
||||
copies: list[_ImageCopy] = []
|
||||
try:
|
||||
for block in blocks:
|
||||
if len(block.url) <= _SMALL_IMAGE_BYTES:
|
||||
continue
|
||||
try:
|
||||
raw = base64.b64decode(block.url.split(";base64,", 1)[1], validate=True)
|
||||
with Image.open(io.BytesIO(raw)) as original:
|
||||
if getattr(original, "is_animated", False) is True:
|
||||
continue
|
||||
original.load()
|
||||
# Preserve PNG pixels and transparency instead of flattening them into JPEG.
|
||||
format = "PNG" if (
|
||||
original.format == "PNG" or "A" in original.getbands()
|
||||
or "transparency" in original.info
|
||||
) else "JPEG"
|
||||
source = ImageOps.exif_transpose(original)
|
||||
if format == "JPEG" and source.mode != "RGB":
|
||||
source = source.convert("RGB")
|
||||
copies.append(_ImageCopy(block, source, format, len(raw), len(raw), source.size))
|
||||
except (ValueError, OSError, Image.DecompressionBombError) as exc:
|
||||
logger.info("Inline image preparation skipped: type={}", type(exc).__name__)
|
||||
|
||||
# Re-encode at the original resolution first. Bound quality loss and any later scaling.
|
||||
copies.sort(key=lambda image: image.original_bytes, reverse=True)
|
||||
sent_bytes = total_bytes
|
||||
for quality, scale in ((85, 1.0), (75, 1.0), (65, 1.0), (65, 0.85), (65, 0.75)):
|
||||
for image in copies:
|
||||
before_bytes = len(image.target.url)
|
||||
image.encode(quality, scale)
|
||||
sent_bytes += len(image.target.url) - before_bytes
|
||||
if sent_bytes <= INLINE_IMAGE_BYTE_BUDGET:
|
||||
break
|
||||
if sent_bytes <= INLINE_IMAGE_BYTE_BUDGET:
|
||||
break
|
||||
logger.info(
|
||||
"Inline images prepared: count={} encoded_bytes_before={} "
|
||||
"encoded_bytes_after={} budget={} budget_met={} images={}",
|
||||
len(blocks), total_bytes, sent_bytes, INLINE_IMAGE_BYTE_BUDGET,
|
||||
sent_bytes <= INLINE_IMAGE_BYTE_BUDGET,
|
||||
[{
|
||||
"before_size": image.source.size, "after_size": image.sent_size,
|
||||
"before_bytes": image.original_bytes, "after_bytes": image.sent_bytes,
|
||||
} for image in copies[:16]],
|
||||
)
|
||||
return prepared
|
||||
finally:
|
||||
for image in copies:
|
||||
image.source.close()
|
||||
@@ -26,6 +26,7 @@ from nanobot.providers.base import (
|
||||
ProviderCallContext,
|
||||
ProviderConversationState,
|
||||
)
|
||||
from nanobot.providers.images import prepare_inline_images
|
||||
from nanobot.providers.oauth_model_catalog import (
|
||||
OAuthCatalogAuthRequiredError,
|
||||
OAuthModelCatalog,
|
||||
@@ -176,7 +177,7 @@ class OpenAICodexProvider(LLMProvider):
|
||||
*,
|
||||
emit_deltas: bool,
|
||||
) -> LLMResponse:
|
||||
wire_body = without_response_item_ids(request_body)
|
||||
wire_body = await prepare_inline_images(without_response_item_ids(request_body))
|
||||
if session_id:
|
||||
websocket_result = await self._responses.websocket_request(
|
||||
session_id, DEFAULT_CODEX_URL, headers, wire_body,
|
||||
|
||||
@@ -34,6 +34,7 @@ from nanobot.providers.base import (
|
||||
resolve_stream_idle_timeout_s,
|
||||
tool_arguments_json_for_replay,
|
||||
)
|
||||
from nanobot.providers.images import prepare_inline_images
|
||||
from nanobot.providers.openai_responses import ResponsesBackend, responses_state_matches
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -1947,6 +1948,7 @@ class OpenAICompatProvider(LLMProvider):
|
||||
reasoning_effort, tool_choice,
|
||||
extra_headers=affinity,
|
||||
)
|
||||
kwargs = await prepare_inline_images(kwargs)
|
||||
chat_raw = cast(
|
||||
Any,
|
||||
await client.chat.completions.create(**kwargs),
|
||||
@@ -2005,6 +2007,7 @@ class OpenAICompatProvider(LLMProvider):
|
||||
reasoning_effort, tool_choice,
|
||||
extra_headers=affinity,
|
||||
)
|
||||
kwargs = await prepare_inline_images(kwargs)
|
||||
if self._spec and self._spec.name == "zhipu" and tools and on_tool_call_delta:
|
||||
# Z.AI/GLM keeps streaming tool-call arguments behind an
|
||||
# explicit provider flag. Pass it through the OpenAI SDK's
|
||||
|
||||
@@ -17,6 +17,7 @@ from nanobot.providers.base import (
|
||||
ProviderConversationState,
|
||||
resolve_stream_idle_timeout_s,
|
||||
)
|
||||
from nanobot.providers.images import prepare_inline_images
|
||||
from nanobot.providers.openai_responses.compaction import (
|
||||
retained_compaction_messages,
|
||||
split_compaction_input,
|
||||
@@ -244,6 +245,7 @@ class ResponsesBackend:
|
||||
on_response_event: Callable[[dict[str, Any]], Awaitable[None]] | None = None,
|
||||
) -> LLMResponse:
|
||||
options: dict[str, Any] = {"timeout": resolve_stream_idle_timeout_s()}
|
||||
body = await prepare_inline_images(body)
|
||||
if verify is not None:
|
||||
options["verify"] = verify
|
||||
if proxy:
|
||||
@@ -271,6 +273,7 @@ class ResponsesBackend:
|
||||
on_tool_call_delta: Callable[[dict[str, Any]], Awaitable[None]] | None = None,
|
||||
) -> LLMResponse:
|
||||
options: dict[str, Any] = {}
|
||||
body = await prepare_inline_images(body)
|
||||
if extra_headers is not None:
|
||||
options["extra_headers"] = extra_headers
|
||||
idle_timeout = resolve_stream_idle_timeout_s()
|
||||
|
||||
@@ -9,6 +9,7 @@ import hashlib
|
||||
import json
|
||||
import re
|
||||
import ssl
|
||||
import time
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable
|
||||
from typing import Any, cast
|
||||
|
||||
@@ -21,6 +22,13 @@ from nanobot.providers.base import LLMProvider, LLMResponse, resolve_stream_idle
|
||||
from nanobot.providers.openai_responses.backend import ResponsesBackend
|
||||
from nanobot.providers.openai_responses.parsing import ResponsesStreamCapture
|
||||
|
||||
_TRANSPORT_FAILURE_LIMIT = 3
|
||||
|
||||
|
||||
def _close_reason(reason: str) -> str:
|
||||
# Close frames are untrusted and may echo request contents or credentials.
|
||||
return reason if reason in {"", "keepalive ping timeout", "going away", "normal closure"} else "redacted"
|
||||
|
||||
|
||||
def _fingerprint(value: object) -> bytes:
|
||||
return hashlib.sha256(
|
||||
@@ -106,6 +114,7 @@ class ResponsesWebSocketSession:
|
||||
self._prefix_length = 0
|
||||
self._response_id: str | None = None
|
||||
self._http_only = False
|
||||
self._transport_failures = 0
|
||||
|
||||
async def aclose(self) -> None:
|
||||
connection, self._connection = self._connection, None
|
||||
@@ -136,6 +145,7 @@ class ResponsesWebSocketSession:
|
||||
await self.aclose()
|
||||
self._auth_fingerprint = auth_fingerprint
|
||||
self._http_only = False
|
||||
self._transport_failures = 0
|
||||
if self._http_only:
|
||||
return None
|
||||
try:
|
||||
@@ -202,15 +212,25 @@ class ResponsesWebSocketSession:
|
||||
payload["previous_response_id"] = self._response_id
|
||||
capture = ResponsesStreamCapture()
|
||||
response_started = False
|
||||
payload_json = json.dumps(payload, ensure_ascii=False)
|
||||
request_bytes = len(payload_json.encode())
|
||||
started_at = time.monotonic()
|
||||
first_event_s: float | None = None
|
||||
|
||||
async def observe_event(event: dict[str, Any]) -> None:
|
||||
nonlocal response_started
|
||||
nonlocal response_started, first_event_s
|
||||
if first_event_s is None:
|
||||
first_event_s = time.monotonic() - started_at
|
||||
logger.info(
|
||||
"Responses WebSocket first event: request_bytes={} elapsed_s={:.3f}",
|
||||
request_bytes, first_event_s,
|
||||
)
|
||||
event_type = event.get("type")
|
||||
if isinstance(event_type, str) and event_type.startswith("response."):
|
||||
response_started = True
|
||||
|
||||
try:
|
||||
await self._connection.send(json.dumps(payload, ensure_ascii=False))
|
||||
await self._connection.send(payload_json)
|
||||
result = await ResponsesBackend.consume(
|
||||
self._events(self._connection), provider=provider, body=body,
|
||||
on_content_delta=on_content_delta,
|
||||
@@ -227,7 +247,34 @@ class ResponsesWebSocketSession:
|
||||
continue
|
||||
raise
|
||||
except (ConnectionClosed, OSError) as exc:
|
||||
raise ConnectionError("Responses WebSocket connection interrupted") from exc
|
||||
self._transport_failures += 1
|
||||
if self._transport_failures >= _TRANSPORT_FAILURE_LIMIT:
|
||||
self._http_only = True
|
||||
received = exc.rcvd if isinstance(exc, ConnectionClosed) else None
|
||||
sent = exc.sent if isinstance(exc, ConnectionClosed) else None
|
||||
direction = "unknown"
|
||||
if isinstance(exc, ConnectionClosed):
|
||||
if received is not None and (sent is None or exc.rcvd_then_sent):
|
||||
direction = "received"
|
||||
elif sent is not None:
|
||||
direction = "sent"
|
||||
logger.warning(
|
||||
"Responses WebSocket interrupted: request_bytes={} elapsed_s={:.3f} "
|
||||
"first_event_s={} type={} received_code={} received_reason={} "
|
||||
"sent_code={} sent_reason={} direction={} failures={} http_only={}",
|
||||
request_bytes, time.monotonic() - started_at, first_event_s,
|
||||
type(exc).__name__, received.code if received is not None else None,
|
||||
_close_reason(received.reason) if received is not None else None,
|
||||
sent.code if sent is not None else None,
|
||||
_close_reason(sent.reason) if sent is not None else None,
|
||||
direction, self._transport_failures, self._http_only,
|
||||
)
|
||||
# Let the owning retry policy decide whether to replay. In particular,
|
||||
# visible partial output and cancellation must not trigger an HTTP replay.
|
||||
if isinstance(exc, TimeoutError):
|
||||
raise
|
||||
raise ConnectionError("Responses WebSocket connection interrupted") from None
|
||||
self._transport_failures = 0
|
||||
response_id = capture.response.get("id") if capture.response is not None else None
|
||||
if result.provider_state is not None:
|
||||
self._properties_fingerprint = properties_fingerprint
|
||||
@@ -246,10 +293,7 @@ class ResponsesWebSocketSession:
|
||||
|
||||
async def _events(self, connection: ClientConnection) -> AsyncIterator[dict[str, Any]]:
|
||||
while True:
|
||||
try:
|
||||
data = await asyncio.wait_for(connection.recv(), resolve_stream_idle_timeout_s())
|
||||
except (ConnectionClosed, OSError) as exc:
|
||||
raise ConnectionError("Responses WebSocket connection closed before completion") from exc
|
||||
data = await asyncio.wait_for(connection.recv(), resolve_stream_idle_timeout_s())
|
||||
try:
|
||||
raw: object = json.loads(data)
|
||||
except ValueError:
|
||||
|
||||
@@ -39,6 +39,7 @@ dependencies = [
|
||||
"lxml-html-clean>=0.4.0,<1.0.0",
|
||||
"rich>=14.0.0,<15.0.0",
|
||||
"qrcode[pil]>=8.0",
|
||||
"pillow>=11.0,<13.0",
|
||||
"croniter>=6.0.0,<7.0.0",
|
||||
"prompt-toolkit>=3.0.50,<4.0.0",
|
||||
"setproctitle>=1.3.7,<2.0.0; sys_platform != 'win32'",
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Exercise inline image preparation at provider SDK and HTTP boundaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import random
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from PIL import Image
|
||||
|
||||
from nanobot.providers.anthropic_provider import AnthropicProvider
|
||||
from nanobot.providers.azure_openai_provider import AzureOpenAIProvider
|
||||
from nanobot.providers.base import ProviderCallContext
|
||||
from nanobot.providers.bedrock_provider import BedrockProvider
|
||||
from nanobot.providers.github_copilot_provider import GitHubCopilotProvider
|
||||
from nanobot.providers.openai_compat_provider import OpenAICompatProvider
|
||||
from nanobot.providers.registry import find_by_name
|
||||
from nanobot.providers.xai_grok_provider import XAIGrokProvider
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def image_blocks():
|
||||
noise = random.Random(234).randbytes(900 * 1800)
|
||||
screenshot = Image.frombytes("L", (900, 1800), noise).point(lambda x: 240 + x // 16)
|
||||
jpeg = io.BytesIO()
|
||||
screenshot.save(jpeg, "JPEG", quality=95)
|
||||
transparent = io.BytesIO()
|
||||
Image.new("RGBA", (700, 700), (20, 60, 100, 80)).save(transparent, "PNG", compress_level=0)
|
||||
thumbnail = io.BytesIO()
|
||||
Image.new("RGB", (32, 32), "white").save(thumbnail, "JPEG", quality=95)
|
||||
images = [("jpeg", jpeg.getvalue())] * 3 + [("png", transparent.getvalue()), ("jpeg", thumbnail.getvalue())]
|
||||
return [
|
||||
{"type": "image_url", "image_url": {
|
||||
"url": f"data:image/{mime};base64,{base64.b64encode(raw).decode()}",
|
||||
}}
|
||||
for mime, raw in images
|
||||
]
|
||||
|
||||
|
||||
def _messages(blocks):
|
||||
return [{"role": "user", "content": [{"type": "text", "text": "Read these images."}, *blocks]}]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def image_peer(monkeypatch):
|
||||
requests = []
|
||||
reject = {"images": False, "text": False}
|
||||
|
||||
async def handle(request):
|
||||
body = await request.json()
|
||||
requests.append((request.path, body))
|
||||
if request.path.endswith("responses"):
|
||||
has_images = "input_image" in json.dumps(body["input"])
|
||||
if reject["images"] and (has_images or reject["text"]):
|
||||
return web.json_response({"error": {
|
||||
"type": "invalid_request_error", "code": "unsupported_image",
|
||||
"message": "This Responses API does not support input_image.",
|
||||
}}, status=400)
|
||||
output = [{"type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
|
||||
"content": [{"type": "output_text", "text": "answer", "annotations": []}]}]
|
||||
response = {
|
||||
"id": f"resp_{len(requests)}", "object": "response", "created_at": 1,
|
||||
"status": "completed", "model": body["model"], "output": output,
|
||||
"usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15},
|
||||
}
|
||||
events = [
|
||||
{"type": "response.output_text.delta", "delta": "answer"},
|
||||
{"type": "response.output_item.done", "output_index": 0, "item": output[0]},
|
||||
{"type": "response.completed", "response": response},
|
||||
]
|
||||
elif request.path.endswith("messages"):
|
||||
response = {
|
||||
"id": "msg_1", "type": "message", "role": "assistant", "model": body["model"],
|
||||
"content": [{"type": "text", "text": "answer"}], "stop_reason": "end_turn",
|
||||
"stop_sequence": None, "usage": {"input_tokens": 10, "output_tokens": 5},
|
||||
}
|
||||
events = [
|
||||
{"type": "message_start", "message": {**response, "content": [], "stop_reason": None}},
|
||||
{"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
|
||||
{"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "answer"}},
|
||||
{"type": "content_block_stop", "index": 0},
|
||||
{"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None},
|
||||
"usage": {"output_tokens": 5}},
|
||||
{"type": "message_stop"},
|
||||
]
|
||||
else:
|
||||
response = {
|
||||
"id": "chat_1", "object": "chat.completion", "created": 1, "model": body["model"],
|
||||
"choices": [{"index": 0, "message": {"role": "assistant", "content": "answer"}, "finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
||||
}
|
||||
events = [{
|
||||
"id": "chat_1", "object": "chat.completion.chunk", "created": 1, "model": body["model"],
|
||||
"choices": [{"index": 0, "delta": {"content": "answer"}, "finish_reason": "stop"}],
|
||||
}]
|
||||
if not body.get("stream"):
|
||||
return web.json_response(response)
|
||||
data = "".join(f"event: {event.get('type', 'message')}\ndata: {json.dumps(event)}\n\n" for event in events)
|
||||
return web.Response(text=data, content_type="text/event-stream")
|
||||
|
||||
async def token(_request):
|
||||
return web.json_response({"token": "copilot-fixture", "expires_at": 4_000_000_000})
|
||||
|
||||
app = web.Application(client_max_size=16 * 1024 * 1024)
|
||||
app.router.add_post("/{path:.*}", handle)
|
||||
app.router.add_get("/copilot_token", token)
|
||||
runner = web.AppRunner(app)
|
||||
await runner.setup()
|
||||
await web.TCPSite(runner, "127.0.0.1", 0).start()
|
||||
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
|
||||
monkeypatch.setenv("no_proxy", "127.0.0.1")
|
||||
monkeypatch.delenv("LANGFUSE_SECRET_KEY", raising=False)
|
||||
try:
|
||||
yield f"http://127.0.0.1:{runner.addresses[0][1]}", requests, reject
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
def _provider(adapter, url, monkeypatch, api_type=None):
|
||||
if adapter == "azure":
|
||||
return AzureOpenAIProvider(api_key="fixture", api_base=url, default_model="gpt-5.4")
|
||||
if adapter == "anthropic":
|
||||
return AnthropicProvider(api_key="fixture", api_base=url)
|
||||
if adapter == "copilot":
|
||||
monkeypatch.setenv("NANOBOT_COPILOT_BASE_URL", f"{url}/v1")
|
||||
monkeypatch.setenv("NANOBOT_COPILOT_TOKEN_URL", f"{url}/copilot_token")
|
||||
monkeypatch.setattr("nanobot.providers.github_copilot_provider._load_github_token",
|
||||
lambda: SimpleNamespace(access="github-fixture"))
|
||||
return GitHubCopilotProvider(default_model="github-copilot/gpt-5.4-mini")
|
||||
if adapter == "xai":
|
||||
monkeypatch.setattr("nanobot.providers.xai_grok_provider.DEFAULT_XAI_GROK_URL", f"{url}/v1/responses")
|
||||
monkeypatch.setattr("nanobot.providers.xai_grok_provider.get_xai_oauth_token",
|
||||
lambda **_: SimpleNamespace(access="xai-fixture"))
|
||||
return XAIGrokProvider(extra_body={"tools": []})
|
||||
spec = find_by_name("deepseek" if adapter == "deepseek" else "openai")
|
||||
return OpenAICompatProvider(
|
||||
api_key="fixture", api_base=f"{url}/v1", spec=spec,
|
||||
default_model="deepseek-v4-flash-vision-exp" if adapter == "deepseek" else "gpt-5.4",
|
||||
api_type=api_type or ("chat_completions" if adapter == "chat" else "responses"), extra_body={"tools": []},
|
||||
)
|
||||
|
||||
|
||||
def _received_images(body):
|
||||
images = []
|
||||
for item in body.get("input", body.get("messages", [])):
|
||||
content = item.get("output") if item.get("type") == "function_call_output" else item.get("content")
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for block in content:
|
||||
if block["type"] == "input_image":
|
||||
images.append(base64.b64decode(block["image_url"].split(",", 1)[1]))
|
||||
elif block["type"] == "image_url":
|
||||
images.append(base64.b64decode(block["image_url"]["url"].split(",", 1)[1]))
|
||||
elif block["type"] == "image":
|
||||
images.append(base64.b64decode(block["source"]["data"]))
|
||||
return images
|
||||
|
||||
|
||||
def _assert_prepared(images, blocks):
|
||||
assert len(images) == 5
|
||||
assert sum(4 * ((len(raw) + 2) // 3) + len("data:image/jpeg;base64,") for raw in images) <= 1_000_000
|
||||
for raw in images[:3]:
|
||||
with Image.open(io.BytesIO(raw)) as image:
|
||||
assert image.size == (900, 1800)
|
||||
with Image.open(io.BytesIO(images[3])) as image:
|
||||
assert image.mode == "RGBA"
|
||||
assert image.size == (700, 700)
|
||||
assert image.getpixel((0, 0)) == (20, 60, 100, 80)
|
||||
assert images[4] == base64.b64decode(blocks[4]["image_url"]["url"].split(",", 1)[1])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("adapter", ["openai", "azure", "deepseek", "copilot", "xai", "chat", "anthropic"])
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
async def test_providers_prepare_image_copies(image_peer, image_blocks, monkeypatch, adapter, streaming):
|
||||
url, requests, _ = image_peer
|
||||
provider = _provider(adapter, url, monkeypatch)
|
||||
messages = _messages(image_blocks)
|
||||
original = json.dumps(messages)
|
||||
try:
|
||||
call = provider.chat_stream if streaming else provider.chat
|
||||
result = await call(messages)
|
||||
assert result.content == "answer"
|
||||
assert result.finish_reason == "stop"
|
||||
assert len(requests) == 1
|
||||
_assert_prepared(_received_images(requests[0][1]), image_blocks)
|
||||
assert json.dumps(messages) == original
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
async def test_bedrock_prepares_images_before_native_conversion(image_blocks, streaming):
|
||||
class Client:
|
||||
requests = []
|
||||
|
||||
def converse(self, **body):
|
||||
self.requests.append(body)
|
||||
return {"output": {"message": {"content": [{"text": "answer"}]}}, "stopReason": "end_turn"}
|
||||
|
||||
def converse_stream(self, **body):
|
||||
self.requests.append(body)
|
||||
return {"stream": iter([
|
||||
{"contentBlockDelta": {"contentBlockIndex": 0, "delta": {"text": "answer"}}},
|
||||
{"messageStop": {"stopReason": "end_turn"}},
|
||||
])}
|
||||
|
||||
client = Client()
|
||||
provider = BedrockProvider(client=client)
|
||||
messages = _messages(image_blocks)
|
||||
original = json.dumps(messages)
|
||||
result = await (provider.chat_stream if streaming else provider.chat)(messages)
|
||||
assert result.content == "answer"
|
||||
images = [block["image"]["source"]["bytes"] for message in client.requests[0]["messages"]
|
||||
for block in message["content"] if "image" in block]
|
||||
_assert_prepared(images, image_blocks)
|
||||
assert json.dumps(messages) == original
|
||||
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
@pytest.mark.parametrize("reject_text", [False, True])
|
||||
async def test_responses_image_rejection_discards_replay_and_retries_once(
|
||||
image_peer, image_blocks, monkeypatch, streaming, reject_text,
|
||||
):
|
||||
url, requests, reject = image_peer
|
||||
provider = _provider("azure", url, monkeypatch)
|
||||
messages = _messages(image_blocks)
|
||||
try:
|
||||
first = await provider.chat(messages)
|
||||
assert first.provider_state is not None
|
||||
pending = {"role": "user", "content": "Continue."}
|
||||
messages.extend([{"role": "assistant", "content": first.content}, pending])
|
||||
reject.update(images=True, text=reject_text)
|
||||
call = provider.chat_stream_with_retry if streaming else provider.chat_with_retry
|
||||
result = await call(messages, provider_context=ProviderCallContext(
|
||||
session_id="image-rejection", conversation_state=first.provider_state.with_pending_messages([pending]),
|
||||
))
|
||||
assert result.finish_reason == ("error" if reject_text else "stop")
|
||||
assert len(requests) == 3
|
||||
assert "input_image" in json.dumps(requests[1][1]["input"])
|
||||
assert "input_image" not in json.dumps(requests[2][1]["input"])
|
||||
assert "not delivered to model" in json.dumps(requests[2][1]["input"])
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
async def test_auto_responses_fallback_keeps_prepared_images(image_peer, image_blocks, monkeypatch, streaming):
|
||||
url, requests, reject = image_peer
|
||||
provider = _provider("deepseek", url, monkeypatch, api_type="auto")
|
||||
reject["images"] = True
|
||||
try:
|
||||
result = await (provider.chat_stream if streaming else provider.chat)(_messages(image_blocks))
|
||||
assert result.content == "answer"
|
||||
assert [path for path, _ in requests] == ["/v1/responses", "/v1/chat/completions"]
|
||||
for _, body in requests:
|
||||
_assert_prepared(_received_images(body), image_blocks)
|
||||
finally:
|
||||
await provider.aclose()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
async def test_text_only_model_keeps_its_image_policy(image_peer, image_blocks, streaming):
|
||||
url, requests, _ = image_peer
|
||||
provider = OpenAICompatProvider(
|
||||
api_key="fixture", api_base=f"{url}/v1", spec=find_by_name("deepseek"),
|
||||
default_model="deepseek-v4-flash", api_type="responses", extra_body={"tools": []},
|
||||
)
|
||||
try:
|
||||
result = await (provider.chat_stream if streaming else provider.chat)(_messages(image_blocks))
|
||||
assert result.content == "answer"
|
||||
assert "input_image" not in json.dumps(requests[0][1])
|
||||
assert "data:image/" not in json.dumps(requests[0][1])
|
||||
assert "Read these images." in json.dumps(requests[0][1])
|
||||
finally:
|
||||
await provider.aclose()
|
||||
@@ -5,13 +5,17 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import random
|
||||
from dataclasses import dataclass, field, replace
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from loguru import logger
|
||||
from PIL import Image
|
||||
from pypdf import PdfWriter
|
||||
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
@@ -173,6 +177,105 @@ async def test_gateway_continues_image_then_pdf_attachment_turn(codex_peer, tmp_
|
||||
await asyncio.wait_for(server.peers[0].closed.wait(), 2)
|
||||
|
||||
|
||||
async def test_gateway_prepares_image_batch_and_preserves_originals(codex_peer, tmp_path):
|
||||
provider, server, _ = codex_peer
|
||||
random_bytes = random.Random(234).randbytes(900 * 1800)
|
||||
image = Image.frombytes("L", (900, 1800), random_bytes).point(lambda x: 240 + x // 16)
|
||||
paths = [tmp_path / f"screenshot-{number}.jpg" for number in range(3)]
|
||||
for path in paths:
|
||||
image.save(path, "JPEG", quality=95)
|
||||
originals = [path.read_bytes() for path in paths]
|
||||
# Each image fits by itself; the combined base64 payload requires preparation.
|
||||
original_sizes = [4 * ((len(raw) + 2) // 3) for raw in originals]
|
||||
assert max(original_sizes) < 1_000_000 < sum(original_sizes)
|
||||
small = tmp_path / "thumbnail.jpg"
|
||||
Image.new("RGB", (32, 32), "white").save(small, "JPEG", quality=95)
|
||||
small_bytes = small.read_bytes()
|
||||
agent = AgentLoop(
|
||||
bus=MessageBus(), provider=provider, workspace=tmp_path,
|
||||
model=provider.get_default_model(), context_window_tokens=128_000,
|
||||
)
|
||||
try:
|
||||
result = await agent.process_direct(
|
||||
"Read these screenshots.", session_key="websocket:large-images",
|
||||
channel="websocket", chat_id="large-images", media=[str(path) for path in [*paths, small]],
|
||||
)
|
||||
assert result.content == "answer"
|
||||
initial = server.requests[0][1]
|
||||
urls = [block["image_url"] for item in initial["input"] for block in item.get("content", []) if block["type"] == "input_image"]
|
||||
assert len(urls) == 4
|
||||
assert sum(map(len, urls)) <= 1_000_000
|
||||
for url in urls[:3]:
|
||||
with Image.open(io.BytesIO(base64.b64decode(url.split(",", 1)[1]))) as sent:
|
||||
assert sent.size == (900, 1800)
|
||||
assert base64.b64decode(urls[3].split(",", 1)[1]) == small_bytes
|
||||
assert [path.read_bytes() for path in paths] == originals
|
||||
|
||||
next_result = await agent.process_direct(
|
||||
"Continue.", session_key="websocket:large-images",
|
||||
channel="websocket", chat_id="large-images",
|
||||
)
|
||||
assert next_result.content == "answer"
|
||||
continued = server.requests[1][1]
|
||||
assert continued["previous_response_id"] == "resp_1"
|
||||
assert "input_image" not in json.dumps(continued["input"])
|
||||
finally:
|
||||
await agent.aclose()
|
||||
|
||||
|
||||
async def test_codex_prepares_tool_images_and_preserves_png_transparency(codex_peer):
|
||||
provider, server, _ = codex_peer
|
||||
random_bytes = random.Random(234).randbytes(1080 * 2376)
|
||||
image = Image.frombytes("L", (1080, 2376), random_bytes).point(lambda x: 240 + x // 16)
|
||||
image_data = io.BytesIO()
|
||||
image.save(image_data, "JPEG", quality=98)
|
||||
transparent = Image.new("RGBA", (700, 700), (20, 60, 100, 80))
|
||||
png_data = io.BytesIO()
|
||||
transparent.save(png_data, "PNG", compress_level=0)
|
||||
images = [
|
||||
{"type": "image_url", "image_url": {"url": f"data:{mime};base64,{base64.b64encode(raw).decode()}"}}
|
||||
for mime, raw in [("image/jpeg", image_data.getvalue()), ("image/png", png_data.getvalue())]
|
||||
]
|
||||
message = {"role": "tool", "tool_call_id": "call_1", "content": images}
|
||||
original_message = json.dumps(message)
|
||||
assistant = {"role": "assistant", "content": "", "tool_calls": [{
|
||||
"id": "call_1", "type": "function",
|
||||
"function": {"name": "read_file", "arguments": '{"path":"image.jpg"}'},
|
||||
}]}
|
||||
result = await provider.chat(
|
||||
[*_messages("Read the image."), assistant, message], provider_context=_context(),
|
||||
)
|
||||
assert result.content == "answer"
|
||||
output = server.requests[0][1]["input"][-1]["output"]
|
||||
urls = [block["image_url"] for block in output]
|
||||
assert sum(map(len, urls)) <= 1_000_000
|
||||
assert len(base64.b64decode(urls[0].split(",", 1)[1])) < len(image_data.getvalue())
|
||||
with Image.open(io.BytesIO(base64.b64decode(urls[1].split(",", 1)[1]))) as sent_png:
|
||||
assert sent_png.mode == "RGBA"
|
||||
assert sent_png.size == transparent.size
|
||||
assert sent_png.tobytes() == transparent.tobytes()
|
||||
assert json.dumps(message) == original_message
|
||||
|
||||
|
||||
async def test_codex_image_budget_limits_downscaling(codex_peer):
|
||||
provider, server, _ = codex_peer
|
||||
image = Image.frombytes("RGB", (1600, 1600), random.Random(234).randbytes(1600 * 1600 * 3))
|
||||
original = io.BytesIO()
|
||||
image.save(original, "JPEG", quality=98)
|
||||
url = "data:image/jpeg;base64," + base64.b64encode(original.getvalue()).decode()
|
||||
assert len(url) > 1_000_000
|
||||
result = await provider.chat(
|
||||
_messages([{"type": "image_url", "image_url": {"url": url}}]),
|
||||
provider_context=_context(),
|
||||
)
|
||||
assert result.content == "answer"
|
||||
sent_url = server.requests[0][1]["input"][0]["content"][0]["image_url"]
|
||||
assert len(sent_url) <= 1_000_000
|
||||
with Image.open(io.BytesIO(base64.b64decode(sent_url.split(",", 1)[1]))) as sent:
|
||||
assert 1200 <= sent.width < 1600
|
||||
assert 1200 <= sent.height < 1600
|
||||
|
||||
|
||||
async def test_codex_continues_attachment_and_tool_turns_without_replaying_history(codex_peer):
|
||||
provider, server, _ = codex_peer
|
||||
reasoning = {
|
||||
@@ -423,13 +526,18 @@ async def test_codex_interrupted_stream_does_not_replay_accepted_request(codex_p
|
||||
|
||||
async def respond(peer, _body):
|
||||
await peer.socket.send_json({"type": "response.output_text.delta", "delta": "partial"})
|
||||
await peer.socket.close(code=1011, message=b"PRIVATE INPUT")
|
||||
await peer.socket.close(code=1011, message=b"PRIVATE INPUT test-token")
|
||||
|
||||
async def on_delta(delta):
|
||||
deltas.append(delta)
|
||||
|
||||
server.respond = respond
|
||||
result = await provider.chat_stream(_messages(), provider_context=_context(), on_content_delta=on_delta)
|
||||
logs = []
|
||||
sink_id = logger.add(lambda message: logs.append(str(message)))
|
||||
try:
|
||||
result = await provider.chat_stream(_messages(), provider_context=_context(), on_content_delta=on_delta)
|
||||
finally:
|
||||
logger.remove(sink_id)
|
||||
assert result.finish_reason == "error"
|
||||
assert result.error_kind == "connection"
|
||||
assert result.error_should_retry is True
|
||||
@@ -438,6 +546,81 @@ async def test_codex_interrupted_stream_does_not_replay_accepted_request(codex_p
|
||||
assert len(server.requests) == 1
|
||||
assert not server.http_requests
|
||||
assert "PRIVATE INPUT" not in result.content
|
||||
log = "\n".join(logs)
|
||||
assert "received_code=1011" in log
|
||||
assert "received_reason=redacted" in log
|
||||
assert "direction=received" in log
|
||||
assert "PRIVATE INPUT" not in log
|
||||
assert "test-token" not in log
|
||||
|
||||
|
||||
async def test_codex_transport_retry_budget_switches_session_to_http(codex_peer, monkeypatch):
|
||||
provider, server, _ = codex_peer
|
||||
monkeypatch.setattr(provider, "_CHAT_RETRY_DELAYS", (0, 0, 0))
|
||||
|
||||
async def respond(peer, _body):
|
||||
await peer.socket.close(code=1011, message=b"keepalive ping timeout")
|
||||
|
||||
server.respond = respond
|
||||
first = await provider.chat_with_retry(_messages(), provider_context=_context())
|
||||
assert first.content == "answer"
|
||||
assert len(server.requests) == 3
|
||||
assert len(server.http_requests) == 1
|
||||
|
||||
second = await provider.chat(_messages("next"), provider_context=_context(first))
|
||||
assert second.content == "answer"
|
||||
assert len(server.requests) == 3
|
||||
assert len(server.http_requests[1]["input"]) == 3
|
||||
assert "previous_response_id" not in server.http_requests[1]
|
||||
|
||||
server.respond = server._respond
|
||||
other = await provider.chat(_messages(), provider_context=_context(session="session-b"))
|
||||
assert other.content == "answer"
|
||||
assert len(server.requests) == 4
|
||||
assert len(server.http_requests) == 2
|
||||
|
||||
|
||||
async def test_codex_transport_fallback_does_not_repeat_partial_output(codex_peer, monkeypatch):
|
||||
provider, server, _ = codex_peer
|
||||
monkeypatch.setattr(provider, "_CHAT_RETRY_DELAYS", (0, 0, 0))
|
||||
deltas = []
|
||||
|
||||
async def respond(peer, _body):
|
||||
if len(server.requests) == 3:
|
||||
await peer.socket.send_json({"type": "response.output_text.delta", "delta": "partial"})
|
||||
await peer.socket.close(code=1011, message=b"keepalive ping timeout")
|
||||
|
||||
async def on_delta(delta):
|
||||
deltas.append(delta)
|
||||
|
||||
server.respond = respond
|
||||
result = await provider.chat_stream_with_retry(
|
||||
_messages(), provider_context=_context(), on_content_delta=on_delta,
|
||||
)
|
||||
assert result.finish_reason == "error"
|
||||
assert deltas == ["partial"]
|
||||
assert len(server.requests) == 3
|
||||
assert not server.http_requests
|
||||
|
||||
next_result = await provider.chat(_messages("next"), provider_context=_context())
|
||||
assert next_result.content == "answer"
|
||||
assert len(server.requests) == 3
|
||||
assert len(server.http_requests) == 1
|
||||
|
||||
|
||||
async def test_codex_idle_timeout_budget_switches_session_to_http(codex_peer, monkeypatch):
|
||||
provider, server, _ = codex_peer
|
||||
monkeypatch.setattr(provider, "_CHAT_RETRY_DELAYS", (0, 0, 0))
|
||||
monkeypatch.setenv("NANOBOT_STREAM_IDLE_TIMEOUT_S", "0.05")
|
||||
|
||||
async def respond(_peer, _body):
|
||||
pass
|
||||
|
||||
server.respond = respond
|
||||
result = await provider.chat_with_retry(_messages(), provider_context=_context())
|
||||
assert result.content == "answer"
|
||||
assert len(server.requests) == 3
|
||||
assert len(server.http_requests) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event", [
|
||||
|
||||
Reference in new issue
Block a user