Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/freehand/runtime/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1161,7 +1161,8 @@ def _send_request(self, token: str | None, kind: str) -> dict[str, Any]:
return self._send_once(token, kind)
except _providers.HTTPStatusError as exc:
err = ModelError(exc.status, exc.body)
if exc.status < 500 or err.code in NON_RETRYABLE_CODES or attempt == limit:
# Some servers (Apple's `fm serve`) report an overflow as a 5xx; resending cannot make it fit.
if exc.status < 500 or err.code in NON_RETRYABLE_CODES or _compaction.overflow(err) or attempt == limit:
raise
wait = exc.retry_after if exc.retry_after is not None else retry_delay(attempt)
if not self._backoff(wait, f"HTTP {exc.status}", attempt, exc.status, error_detail(exc.body),
Expand Down Expand Up @@ -1289,7 +1290,7 @@ def call_model(self) -> dict[str, Any]:
except StreamFailure as exc:
self._check_cancel()
last = ModelError(429 if exc.code == USAGE_LIMIT_CODE else 200, exc.body)
if (exc.code in NON_RETRYABLE_CODES or image_input_error(exc.body)
if (exc.code in NON_RETRYABLE_CODES or image_input_error(exc.body) or _compaction.overflow(last)
or (self.edited_pending and last.rejects_transcript_edit())):
raise last from None
retry_after = exc.retry_after
Expand Down Expand Up @@ -1764,7 +1765,8 @@ def run_turn(self, interactive: bool = False) -> tuple[str, str]:
return "stopped_usage_limit", ("Usage limit reached on your ChatGPT plan (or on Freehand's share "
f"of it). Manage usage: {_auth.USAGE_URL}")
if exc.code == "context_length_exceeded" or re.search(
r"context (length|window)|maximum context|prompt is too long|input token count.*exceeds",
r"context (length|window)|maximum context|prompt is too long|input token count.*exceeds|"
r"exceeded the model's context size",
exc.body, re.I):
window = f" of {int(self.cfg['context_window']):,}" if self.cfg.get("context_window") else ""
return "context_full", (f"the context no longer fits the model's window{window} tokens "
Expand Down
3 changes: 2 additions & 1 deletion src/freehand/runtime/compaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,4 +257,5 @@ def overflow(exc: Any) -> bool:
or bool(re.search(r"context[_ ](?:length|window).*(?:exceed|limit)|exceeds.*context (?:window|length)|"
r"maximum context|prompt (?:is )?too long|input token count.*exceeds|"
r"maximum prompt length|exceeded model token limit|context window exceeds|"
r"reduce the length of the messages|exceeds the available context size", body, re.I)))
r"reduce the length of the messages|exceeds the available context size|"
r"exceeded the model's context size", body, re.I)))
42 changes: 42 additions & 0 deletions tests/test_context_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import json
from http.server import BaseHTTPRequestHandler

import pytest

from fakes import FakeAuth, FakeResponses, call, developer_texts, say, load_runtime, make_session, send_json, transcript
from freehand import session, ui
from test_runtime import serve
Expand Down Expand Up @@ -70,6 +72,46 @@ def do_POST(self):
assert status == "context_full" and "272,000" in summary


FM_OVERFLOW = {"error": {"message": "The session's transcript exceeded the model's context size.",
"type": "server_error", "code": "500"}}


@pytest.mark.parametrize("stream", [True, False])
def test_apple_fm_overflow_is_context_full_and_not_retried(tmp_path, stream):
# `fm serve` reports overflow as a server error: in-stream after HTTP 200, or HTTP 500 without streaming.
# Each retry would resend the whole conversation against Apple's daily PCC quota.
posts = []

class Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass

def do_POST(self):
posts.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))
if not stream:
return send_json(self, 500, FM_OVERFLOW)
data = (b'data: {"choices":[{"index":0,"delta":{"role":"assistant"}}]}\n\n'
b"event: error\ndata: " + json.dumps(FM_OVERFLOW).encode() + b"\n\n")
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)

server, url = serve(Handler)
try:
h = make_session(tmp_path, url, provider="openai-chat", model="pcc", auth="none", stream=stream,
context_window=32768)
agent = load_runtime(h).Agent(h)
agent.start()
status, summary = agent.submit("hello")
finally:
server.shutdown()
server.server_close()
assert status == "context_full" and "32,768" in summary
assert len(posts) == 1


def test_status_bar_shows_used_over_window(tmp_path):
h = make_session(tmp_path, "http://127.0.0.1:1", context_window=500000, model="gpt-6.1-sol")
agent = load_runtime(h).Agent(h)
Expand Down
Loading