diff --git a/apps/albedo/src/albedo/kernel.gleam b/apps/albedo/src/albedo/kernel.gleam index b1335bf67..f1ce0870f 100644 --- a/apps/albedo/src/albedo/kernel.gleam +++ b/apps/albedo/src/albedo/kernel.gleam @@ -143,7 +143,7 @@ pub fn execute( timeout_ms, False, types.any_images, - types.request_clip_budget, + types.any_images.clip_budget, False, None, ) @@ -200,6 +200,7 @@ fn run( #("media", json.array(images.media, json.string)), #("max_fps", json.nullable(images.fidelity.max_fps, json.float)), #("clip_room", json.int(int.max(clip_room, 0))), + #("max_clip_bytes", json.int(images.max_clip_bytes)), #("snapshots", json.bool(snapshots)), #("timeout_ms", json.int(timeout_ms)), ]) diff --git a/apps/albedo/src/albedo/kernel/python_tool.gleam b/apps/albedo/src/albedo/kernel/python_tool.gleam index 5f1cd2711..43bf613de 100644 --- a/apps/albedo/src/albedo/kernel/python_tool.gleam +++ b/apps/albedo/src/albedo/kernel/python_tool.gleam @@ -202,7 +202,7 @@ fn outcome_output( None -> #([image, ..kept.0], kept.1) } }) - let #(images, over) = within_room(images, context.clip_room) + let #(images, over) = within_room(images, context.clip_room, limits) python.Outcome( ..outcome, images: images, @@ -244,8 +244,9 @@ fn outcome_output( pub fn within_room( images: List(types.Image), room: Int, + limits: types.ImageLimits, ) -> #(List(types.Image), List(String)) { - let held = types.request_clip_budget - room + let held = limits.clip_budget - room let #(_, kept, over) = list.fold(images, #(0, [], []), fn(acc, image) { let #(adding, kept, over) = acc @@ -254,7 +255,9 @@ pub fn within_room( case types.media_kind(image) { types.Picture -> #(adding, [image, ..kept], over) _ -> - case types.clip_budget_refusal(held, adding + size) { + case + types.clip_budget_refusal(limits.clip_budget, held, adding + size) + { None -> #(adding + size, [image, ..kept], over) Some(reason) -> #(adding, kept, [ mime_type diff --git a/apps/albedo/src/albedo/model_loop/loop.gleam b/apps/albedo/src/albedo/model_loop/loop.gleam index 8a33284a1..24717054b 100644 --- a/apps/albedo/src/albedo/model_loop/loop.gleam +++ b/apps/albedo/src/albedo/model_loop/loop.gleam @@ -649,7 +649,7 @@ fn converse( list.find(turn.call_indices, fn(binding) { binding.0 == call.id }) case output_index { Ok(binding) -> { - let room = types.request_clip_budget - held + let room = limits.clip_budget - held use item <- result.map(run_tool( state, id, diff --git a/apps/albedo/src/albedo/runtime.gleam b/apps/albedo/src/albedo/runtime.gleam index b8c68ead7..67be3c827 100644 --- a/apps/albedo/src/albedo/runtime.gleam +++ b/apps/albedo/src/albedo/runtime.gleam @@ -980,7 +980,7 @@ pub fn execute( code, timeout_ms, types.any_images, - types.request_clip_budget, + types.any_images.clip_budget, False, False, ) @@ -2636,6 +2636,14 @@ pub fn upstream( upstream.images.media, upstream.endpoint <> "\n" <> model, ), + clip_budget: int.min( + upstream.images.clip_budget, + types.request_clip_budget, + ), + max_clip_bytes: int.min( + upstream.images.max_clip_bytes, + types.max_clip_bytes, + ), fidelity: media_facts.fidelity( provider, upstream.endpoint, @@ -2702,7 +2710,7 @@ fn readable_requests( request.input |> list.map(types.readable_input(limits, _)) |> media_copies.apply(ledger, limits, _) - |> types.within_clip_budget + |> types.within_clip_budget(limits) types.Request(..request, input:) } extension.Upstream( diff --git a/apps/albedo/src/albedo/session.gleam b/apps/albedo/src/albedo/session.gleam index bd8820adb..897266b74 100644 --- a/apps/albedo/src/albedo/session.gleam +++ b/apps/albedo/src/albedo/session.gleam @@ -4986,11 +4986,10 @@ fn over_clip_budget( // an unreadable history fails the turn when it starts instead. Error(_) -> #(state, None) Ok(state) -> { - let held = - types.request_clip_budget - session_history.clip_room(state, limits) + let held = limits.clip_budget - session_history.clip_room(state, limits) #( state, - types.clip_budget_refusal(held, adding) + types.clip_budget_refusal(limits.clip_budget, held, adding) |> option.map(fn(reason) { refusal.MediaBudget( reason diff --git a/apps/albedo/src/albedo/session/session_history.gleam b/apps/albedo/src/albedo/session/session_history.gleam index 349334306..d30af8c3d 100644 --- a/apps/albedo/src/albedo/session/session_history.gleam +++ b/apps/albedo/src/albedo/session/session_history.gleam @@ -146,7 +146,7 @@ pub fn clip_room( runtime.clips_held(state.host, limits, carried(state, entries)) None -> 0 } - types.request_clip_budget - held + limits.clip_budget - held } fn carried( diff --git a/apps/albedo/src/albedo/session/session_shake.gleam b/apps/albedo/src/albedo/session/session_shake.gleam index 6915b044a..e22f65148 100644 --- a/apps/albedo/src/albedo/session/session_shake.gleam +++ b/apps/albedo/src/albedo/session/session_shake.gleam @@ -27,8 +27,8 @@ pub fn shake( Ok(media) -> case selectors { [] -> { - let #(state, held) = held(state) - #(state, Ok(listing(media, held))) + let #(state, clips) = clips(state) + #(state, Ok(listing(media, clips))) } _ -> case busy(state), chosen(media, selectors) { @@ -173,7 +173,7 @@ fn drop( view.StaleContext, "/sessions/" <> state.info.id <> "/context", ) - let #(state, held) = held(state) + let #(state, clips) = clips(state) let ids = ids(media) let gone = list.filter(media, fn(item) { list.contains(dropped, item.hash) }) @@ -186,7 +186,7 @@ fn drop( #( state, Ok( - answer(left, held, message, [ + answer(left, clips, message, [ #("shaken", json.array(gone, fn(item) { entry(item, ids) })), #("rows", json.int(rows)), ]), @@ -196,7 +196,7 @@ fn drop( } } -fn listing(media: List(images.Media), held: option.Option(Int)) -> json.Json { +fn listing(media: List(images.Media), clips: Clips) -> json.Json { let ids = ids(media) let lines = list.map(media, fn(item) { @@ -218,18 +218,18 @@ fn listing(media: List(images.Media), held: option.Option(Int)) -> json.Json { "; ", ) }) - let held_text = case held { + let held_text = case clips.held { Some(held) -> "; its clips take " <> size_text(held) <> " of the " - <> size_text(types.request_clip_budget) + <> size_text(clips.budget) <> " of clips a request carries" None -> "" } answer( media, - held, + clips, case media { [] -> "This session's history holds no stored pictures or clips." _ -> @@ -253,15 +253,15 @@ fn size_text(bytes: Int) -> String { fn answer( media: List(images.Media), - held: option.Option(Int), + clips: Clips, message: String, extra: List(#(String, json.Json)), ) -> json.Json { let ids = ids(media) json.object([ #("media", json.array(media, fn(item) { entry(item, ids) })), - #("clips_held", json.nullable(held, json.int)), - #("clip_budget", json.int(types.request_clip_budget)), + #("clips_held", json.nullable(clips.held, json.int)), + #("clip_budget", json.int(clips.budget)), #("message", json.string(message)), ..extra ]) @@ -292,22 +292,30 @@ fn entry(item: images.Media, ids: Int) -> json.Json { ]) } -fn held( +/// what the session's next request carries of clips, and the budget its +/// model's wire allows, albedo's own without a provider. +type Clips { + Clips(held: option.Option(Int), budget: Int) +} + +fn clips( state: session_state.State(message), -) -> #(session_state.State(message), option.Option(Int)) { +) -> #(session_state.State(message), Clips) { case session_provider.configured_client(state) { - Error(_) -> #(state, None) - Ok(#(state, client)) -> + Error(_) -> #(state, Clips(None, types.request_clip_budget)) + Ok(#(state, client)) -> { + let budget = client.images.clip_budget case session_history.ensure_history(state) { - Error(_) -> #(state, None) + Error(_) -> #(state, Clips(None, budget)) Ok(state) -> #( state, - Some( - types.request_clip_budget - - session_history.clip_room(state, client.images), + Clips( + Some(budget - session_history.clip_room(state, client.images)), + budget, ), ) } + } } } diff --git a/apps/albedo/test/albedo/composition/snapcompact_test.gleam b/apps/albedo/test/albedo/composition/snapcompact_test.gleam index 016fdc067..4b776e100 100644 --- a/apps/albedo/test/albedo/composition/snapcompact_test.gleam +++ b/apps/albedo/test/albedo/composition/snapcompact_test.gleam @@ -43,6 +43,8 @@ pub fn a_full_frame_renders_inside_the_provider_edge_test() -> Nil { vision: types.default_vision, media: [], frame_rate: False, + clip_budget: types.request_clip_budget, + max_clip_bytes: types.max_clip_bytes, fidelity: types.full_fidelity, ) use model <- list.each(["gemini-3-pro", "gpt-5", "claude-opus-5-5"]) diff --git a/apps/albedo/test/albedo/kernel/tool_image_test.gleam b/apps/albedo/test/albedo/kernel/tool_image_test.gleam index bc8e8059b..c535d1c33 100644 --- a/apps/albedo/test/albedo/kernel/tool_image_test.gleam +++ b/apps/albedo/test/albedo/kernel/tool_image_test.gleam @@ -194,13 +194,18 @@ pub fn clips_past_the_room_stay_back_test() -> Nil { } let assert Ok(picture) = types.stored_image("image/png", "p", 900, fn() { Error(Nil) }, 2, 3, 600) + let limits = types.ImageLimits(..types.any_images, clip_budget: 12_582_912) let #(kept, errors) = - python_tool.within_room([clip(60), picture, clip(50), clip(40)], 100) + python_tool.within_room( + [clip(60), picture, clip(50), clip(40)], + 100, + limits, + ) kept |> should.equal([clip(60), picture, clip(40)]) let assert [error] = errors let assert True = error - == "audio/wav clip not attached: these clips take 0 MiB, and the session's clips already hold 64 MiB of the 64 MiB one request carries; await commands.shake() lists the session's media and drops what it no longer needs" - let #(kept, _) = python_tool.within_room([clip(60)], 0) + == "audio/wav clip not attached: these clips take 0 MiB, and the session's clips already hold 12 MiB of the 12 MiB one request carries; await commands.shake() lists the session's media and drops what it no longer needs" + let #(kept, _) = python_tool.within_room([clip(60)], 0, limits) kept |> should.equal([]) } diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index 4b82c240a..ddddcdd2d 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -7056,7 +7056,7 @@ type ClientInterface interface { // GetSessionMedia List the pictures and clips a session's history holds // - // Each stored picture or clip once, by the first hex digits of its payload hash, with every row that shows it. `clips_held` is the base64 bytes of the clips the session's next request carries, as its model is sent them, which `clip_budget` bounds; null when the session has no provider. + // Each stored picture or clip once, by the first hex digits of its payload hash, with every row that shows it. `clips_held` is the base64 bytes of the clips the session's next request carries, as its model is sent them, which `clip_budget` bounds; null when the session has no provider. `clip_budget` is what the wire of the session's current model takes, held to albedo's own 64 MiB, or that ceiling without a provider. // // Corresponds with GET /sessions/{session_id}/media (the `GetSessionMedia` operationId). GetSessionMedia(ctx context.Context, sessionID ID, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -10520,7 +10520,7 @@ func (c *Client) UpgradeKernel(ctx context.Context, sessionID ID, body UpgradeKe // GetSessionMedia List the pictures and clips a session's history holds // -// Each stored picture or clip once, by the first hex digits of its payload hash, with every row that shows it. `clips_held` is the base64 bytes of the clips the session's next request carries, as its model is sent them, which `clip_budget` bounds; null when the session has no provider. +// Each stored picture or clip once, by the first hex digits of its payload hash, with every row that shows it. `clips_held` is the base64 bytes of the clips the session's next request carries, as its model is sent them, which `clip_budget` bounds; null when the session has no provider. `clip_budget` is what the wire of the session's current model takes, held to albedo's own 64 MiB, or that ceiling without a provider. // // Corresponds with GET /sessions/{session_id}/media (the `GetSessionMedia` operationId). func (c *Client) GetSessionMedia(ctx context.Context, sessionID ID, reqEditors ...RequestEditorFn) (*http.Response, error) { diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 59334e8e6..417a02a7c 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -4059,6 +4059,8 @@ paths: hash, with every row that shows it. `clips_held` is the base64 bytes of the clips the session's next request carries, as its model is sent them, which `clip_budget` bounds; null when the session has no provider. + `clip_budget` is what the wire of the session's current model takes, + held to albedo's own 64 MiB, or that ceiling without a provider. parameters: - name: session_id in: path diff --git a/e2e/media_input_test.py b/e2e/media_input_test.py index b894ad145..d1c9319dc 100644 --- a/e2e/media_input_test.py +++ b/e2e/media_input_test.py @@ -132,8 +132,11 @@ SPOKEN_WAV = wav(200_000) SPOKEN_WAV_DATA = base64.b64encode(SPOKEN_WAV).decode() SHORT_MP3 = mp3(3) SHORT_MP3_DATA = base64.b64encode(SHORT_MP3).decode() -# just under 20 MiB: two fill most of the 64 MiB budget as base64, a third won't fit. -FULL_FRAMES = 50_000 +# two fill most of opencode go's 12 MiB clip budget as base64, a third won't fit. +FULL_FRAMES = 11_000 +# about 5 MiB as base64: three fit the 64 MiB budget an openai chat profile has, +# two fit opencode go's. +WAV_FRAMES = 2_050_000 SHAKEN_WAV = "[audio/wav clip removed by shake]" FFMPEG = """#!/bin/sh tools=$(dirname "$0") @@ -207,7 +210,14 @@ class MediaInputTests(unittest.TestCase): "apiKey": "go-key", "model": model, "protocol": "chat_completions", - } + }, + # the openai wire keeps albedo's own 64 MiB clip budget. + "open": { + "baseUrl": provider.url, + "apiKey": "open-key", + "model": CHAT, + "protocol": "chat_completions", + }, }, prepare=offline, ) @@ -230,13 +240,14 @@ class MediaInputTests(unittest.TestCase): calls = app.root / "media-tools" / "calls" return calls.read_text().splitlines() if calls.exists() else [] - def use(self, app: Albedo, session: str, model: str) -> None: + def use(self, app: Albedo, session: str, model: str, profile: str = "") -> None: with app.api(f"/sessions/{session}/configuration") as response: response.read() etag = response.headers["ETag"] + change = {"model": model, **({"provider_profile": profile} if profile else {})} app.api( f"/sessions/{session}/configuration", - {"model": model}, + change, method="PATCH", headers={"If-Match": etag}, ).close() @@ -433,8 +444,9 @@ class MediaInputTests(unittest.TestCase): self.assertIn("attached audio/wav, 52 bytes", cell_result(result)["output"]) def test_a_cell_shows_a_clip_larger_than_a_result_frame(self) -> None: - # past the kernel link's 8 MiB frame, so the clip crosses in raw parts. - frames = 31_000 + # past the kernel link's 8 MiB frame, so the clip crosses in raw parts, + # and within opencode go's 12 MiB budget as base64. + frames = 20_400 code = f"{inspect.getsource(mp3)}\nprint(show_media(mp3({frames})))" app, provider = self.start( GEMINI, @@ -450,7 +462,7 @@ class MediaInputTests(unittest.TestCase): if answered(request) ] clip = mp3(frames) - self.assertGreater(len(clip), 12 * 1024 * 1024) + self.assertGreater(len(clip), 8 * 1024 * 1024) self.assertEqual( [ (mime, hashlib.sha256(base64.b64decode(data)).hexdigest()) @@ -756,6 +768,8 @@ class MediaInputTests(unittest.TestCase): def test_a_long_wav_is_sized_by_how_long_it_plays(self) -> None: app, provider = self.start(GEMINI, lambda request: text("ok")) session = app.session() + # opencode go's 12 MiB clip budget takes no 13 MB wav, the openai wire's does. + self.use(app, session, GEMINI, "open") route = f"/sessions/{session}/configuration" with app.api(route) as response: etag = response.headers["ETag"] @@ -1175,12 +1189,12 @@ class MediaInputTests(unittest.TestCase): # the history's clips count toward the budget too. refused = self.problem(lambda: self.send(app, session, "a third", uploads[2])) self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) - self.assertIn("already hold 53 MiB of the 64 MiB", refused["detail"]) + self.assertIn("already hold 11.7 MiB of the 12 MiB", refused["detail"]) edited = self.edit_queued(app, provider, session, [{"upload": uploads[2]}]) self.assertEqual((edited["status"], edited["code"]), (409, "media_budget")) listed = self.media(app, session) self.assertEqual(listed["clips_held"], 2 * len(base64.b64encode(full))) - self.assertEqual(listed["clip_budget"], 64 * 1024 * 1024) + self.assertEqual(listed["clip_budget"], 12 * 1024 * 1024) # past the kernel's check, the daemon holds the clip back itself. code = ( @@ -1210,7 +1224,7 @@ class MediaInputTests(unittest.TestCase): ) ) adding = len(base64.b64encode(mp3(30_000))) / 2**20 - room = (64 * 2**20 - listed["clips_held"]) / 2**20 + room = (12 * 2**20 - listed["clips_held"]) / 2**20 self.assertIn( f"these clips take {adding:.1f} MiB as base64, and the session's next " f"request has room for {room:.1f} MiB more; await commands.shake()", @@ -1245,7 +1259,7 @@ class MediaInputTests(unittest.TestCase): [first, sent] = asking(provider, "after compaction") self.assertEqual(inline(first), []) [result] = self.cell_results(sent) - self.assertEqual(result["output"].strip(), str(64 * 1024 * 1024)) + self.assertEqual(result["output"].strip(), str(12 * 1024 * 1024)) self.assertEqual(self.media(app, session)["clips_held"], 0) provider.script = lambda request: text("ok") @@ -1266,7 +1280,7 @@ class MediaInputTests(unittest.TestCase): # chat is sent small copies, so three long wavs fit beside each other. self.encodes(app, "mp3", mp3(3)) session = app.session() - clips = [wav(10_400_000 + index) for index in range(3)] + clips = [wav(WAV_FRAMES + index) for index in range(3)] for index, clip in enumerate(clips): upload = operation_id() self.upload(app, session, upload, "audio/wav", clip).close() @@ -1302,6 +1316,61 @@ class MediaInputTests(unittest.TestCase): refused = self.problem(lambda: self.attach(app, session, "audio/wav", WAV_DATA)) self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) + def test_a_switch_to_a_wire_with_a_smaller_budget_trims_the_same_each_time( + self, + ) -> None: + app, provider = self.start(GEMINI_LONG, lambda request: text("ok")) + session = app.session() + self.use(app, session, CHAT_LONG, "open") + self.assertEqual(self.media(app, session)["clip_budget"], 64 * 1024 * 1024) + # no ffmpeg copy, so every clip goes as it is. + clips = [wav(WAV_FRAMES + index) for index in range(3)] + for index, clip in enumerate(clips): + upload = operation_id() + self.upload(app, session, upload, "audio/wav", clip).close() + with self.send(app, session, f"clip {index}", upload) as response: + self.assertEqual(response.status, 202) + app.idle(session) + + self.use(app, session, GEMINI_LONG, "go") + listed = self.media(app, session) + self.assertEqual(listed["clip_budget"], 12 * 1024 * 1024) + self.assertGreater(listed["clips_held"], listed["clip_budget"]) + provider.requests.clear() + for words in ("first after", "second after"): + app.prompt(session, words).close() + app.idle(session) + first, second = ( + asking(provider, "first after")[0], + asking(provider, "second after")[-1], + ) + sent = [ + hashlib.sha256(base64.b64decode(data)).hexdigest() + for _, data in inline(first) + ] + self.assertEqual(sent, [hashlib.sha256(clip).hexdigest() for clip in clips[1:]]) + self.assertIn( + "[1 clip(s) omitted: newer clips fill this request's media budget]", + json.dumps(first["contents"][0]), + ) + self.assertEqual( + second["contents"][: len(first["contents"])], first["contents"] + ) + refused = self.problem(lambda: self.attach(app, session, "audio/wav", WAV_DATA)) + self.assertEqual((refused["status"], refused["code"]), (409, "media_budget")) + self.assertIn("of the 12 MiB one request carries", refused["detail"]) + + room = "import albedo_cells\nprint(albedo_cells.CELL.get().clip_room)" + provider.script = lambda request: ( + text("done") if answered(request) else python(room) + ) + app.prompt(session, "how much room").close() + app.idle(session) + [result] = self.cell_results( + next(r for r in asking(provider, "how much room") if answered(r)) + ) + self.assertEqual(result["output"].strip(), "0") + def test_shake_drops_media_by_kind_and_by_id(self) -> None: picture = png(2, 2) show = ( diff --git a/extensions/anthropic_api/src/albedo_ext_anthropic_api/extension.gleam b/extensions/anthropic_api/src/albedo_ext_anthropic_api/extension.gleam index fb6b06855..922461129 100644 --- a/extensions/anthropic_api/src/albedo_ext_anthropic_api/extension.gleam +++ b/extensions/anthropic_api/src/albedo_ext_anthropic_api/extension.gleam @@ -122,6 +122,8 @@ fn resolve( types.anthropic_vision, [], False, + types.request_clip_budget, + types.max_clip_bytes, types.full_fidelity, ), output: extension.NoCeiling, diff --git a/extensions/antigravity/src/albedo_ext_antigravity/extension.gleam b/extensions/antigravity/src/albedo_ext_antigravity/extension.gleam index 2e44bbbfd..0b2ec846a 100644 --- a/extensions/antigravity/src/albedo_ext_antigravity/extension.gleam +++ b/extensions/antigravity/src/albedo_ext_antigravity/extension.gleam @@ -35,6 +35,10 @@ import gleam/option.{type Option, None, Some} import gleam/result import gleam/string +/// a 100 MB request carrying a 75 MiB WAV inline went through. nothing is +/// published, so clips keep 64 MiB of it. +const clip_budget = 67_108_864 + pub type Access { Access(token: String, project: String, email: String) } @@ -304,6 +308,8 @@ fn upstream( types.gemini_vision, types.gemini_clips, True, + clip_budget, + types.max_clip_bytes, types.full_fidelity, ) family.GptOss -> @@ -313,6 +319,8 @@ fn upstream( types.openai_vision, [], False, + types.request_clip_budget, + types.max_clip_bytes, types.full_fidelity, ) }, diff --git a/extensions/bedrock/src/albedo_ext_bedrock/extension.gleam b/extensions/bedrock/src/albedo_ext_bedrock/extension.gleam index 6856a18dd..ce3322921 100644 --- a/extensions/bedrock/src/albedo_ext_bedrock/extension.gleam +++ b/extensions/bedrock/src/albedo_ext_bedrock/extension.gleam @@ -225,6 +225,8 @@ fn resolve( types.anthropic_vision, [], False, + types.request_clip_budget, + types.max_clip_bytes, types.full_fidelity, ) _ -> types.anthropic_images diff --git a/extensions/codex/src/albedo_ext_codex/extension.gleam b/extensions/codex/src/albedo_ext_codex/extension.gleam index a94d5e3d9..8ebce1445 100644 --- a/extensions/codex/src/albedo_ext_codex/extension.gleam +++ b/extensions/codex/src/albedo_ext_codex/extension.gleam @@ -268,6 +268,8 @@ fn resolve( types.openai_vision, [], False, + types.request_clip_budget, + types.max_clip_bytes, types.full_fidelity, ), ) diff --git a/extensions/openai/src/albedo_ext_openai/extension.gleam b/extensions/openai/src/albedo_ext_openai/extension.gleam index c6ed449e0..6da96d820 100644 --- a/extensions/openai/src/albedo_ext_openai/extension.gleam +++ b/extensions/openai/src/albedo_ext_openai/extension.gleam @@ -156,6 +156,8 @@ fn resolve( types.Responses -> [] }, False, + types.request_clip_budget, + max_clip_bytes(connection.client.base_url), types.full_fidelity, ), output: output_ceiling(connection.client.base_url), @@ -194,6 +196,26 @@ fn vision_profile(base_url: String) -> types.VisionProfile { } } +/// openai publishes no input_audio limit. azure takes audio files of at most +/// 20 MB. +/// https://learn.microsoft.com/en-us/azure/foundry/openai/audio-completions-quickstart +fn max_clip_bytes(base_url: String) -> Int { + let host = host_of(base_url) + case + list.any( + [ + ".openai.azure.com", + ".cognitiveservices.azure.com", + ".services.ai.azure.com", + ], + string.ends_with(host, _), + ) + { + True -> 20_000_000 + False -> types.max_clip_bytes + } +} + fn is_openrouter(host: String) -> Bool { host == "openrouter.ai" || string.ends_with(host, ".openrouter.ai") } diff --git a/extensions/opencode_go/src/albedo_ext_opencode_go/extension.gleam b/extensions/opencode_go/src/albedo_ext_opencode_go/extension.gleam index de543d61a..e007bfefc 100644 --- a/extensions/opencode_go/src/albedo_ext_opencode_go/extension.gleam +++ b/extensions/opencode_go/src/albedo_ext_opencode_go/extension.gleam @@ -107,6 +107,7 @@ fn resolve( ..types.any_images, media: wire.media(context.model), frame_rate: wire.frame_rate(context.model), + clip_budget: wire.clip_budget, ), ) // Claude models are served on the Messages route, which caches only the diff --git a/extensions/opencode_go/src/albedo_ext_opencode_go/wire.gleam b/extensions/opencode_go/src/albedo_ext_opencode_go/wire.gleam index e4742f94b..b78958823 100644 --- a/extensions/opencode_go/src/albedo_ext_opencode_go/wire.gleam +++ b/extensions/opencode_go/src/albedo_ext_opencode_go/wire.gleam @@ -94,6 +94,12 @@ pub fn media(model: String) -> List(String) { } } +/// nothing is published. its edge took 16 MB bodies and refused one of about +/// 17 MB with a 413, so clips keep 12 MiB, the rest left to text and pictures. +/// https://github.com/anomalyco/opencode/issues/54784 +/// https://github.com/anomalyco/opencode/issues/59067 +pub const clip_budget = 12_582_912 + /// only the gemini route's parts carry a video's frame rate pub fn frame_rate(model: String) -> Bool { route(model) == GeminiRoute diff --git a/extensions/vertex/src/albedo_ext_vertex/extension.gleam b/extensions/vertex/src/albedo_ext_vertex/extension.gleam index 3d275a2e4..af97d7feb 100644 --- a/extensions/vertex/src/albedo_ext_vertex/extension.gleam +++ b/extensions/vertex/src/albedo_ext_vertex/extension.gleam @@ -22,6 +22,11 @@ type Config { Config(project: Option(String), location: Option(String)) } +/// a request takes 500 MiB with its base64 and an inline part 256 MB, so 400 +/// MiB of clips leave text and pictures their room. +/// https://docs.cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference +const clip_budget = 419_430_400 + pub fn extension() -> extension.Extension { extension.Extension( "vertex", @@ -80,6 +85,8 @@ fn resolve( types.gemini_vision, types.gemini_clips, True, + clip_budget, + types.max_clip_bytes, types.full_fidelity, ), extension.NoCeiling, diff --git a/packages/albedo_model/src/albedo_model.gleam b/packages/albedo_model/src/albedo_model.gleam index 57661c324..d79924e69 100644 --- a/packages/albedo_model/src/albedo_model.gleam +++ b/packages/albedo_model/src/albedo_model.gleam @@ -62,12 +62,16 @@ pub const max_image_bytes = 5_242_880 pub const max_image_encoded_bytes = 6_990_508 -/// 20 MiB holds minutes of compressed audio or a short video. +/// albedo's ceiling on one clip, whatever its wire takes: it crosses the +/// kernel link, sits in json as base64 and goes with every request. 20 MiB +/// holds minutes of compressed audio or a short video. pub const max_clip_bytes = 20_971_520 pub const max_clip_encoded_bytes = 27_962_028 -/// antigravity took a 100 MB request. clips may take 64 MiB of it. +/// albedo's ceiling on the base64 clips one request carries, however much +/// its wire takes: every turn sends the whole history's clips again. +/// antigravity took a 100 MB request. pub const request_clip_budget = 67_108_864 pub const max_image_edge = 16_384 @@ -80,8 +84,12 @@ const max_image_pixels = 40_000_000 /// `max_images` is how many one request may carry, when the provider says. /// `vision` is what a renderer needs to size images for the provider. /// `media` is the clip types the wire carries, and `frame_rate` whether it -/// can ask the model to sample a video at a rate. `fidelity` is what the -/// model takes in of a clip: a wire leaves it `full_fidelity`, and +/// can ask the model to sample a video at a rate. `clip_budget` is the base64 +/// bytes of clips one request may carry, leaving the rest of the provider's +/// request limit to text and pictures, and `max_clip_bytes` the most one clip +/// may hold decoded; `runtime.upstream` holds both to albedo's ceilings. A wire +/// without clips leaves them at the ceilings. `fidelity` is what the model +/// takes in of a clip: a wire leaves it `full_fidelity`, and /// `runtime.upstream` fills it from the model facts. pub type ImageLimits { ImageLimits( @@ -90,6 +98,8 @@ pub type ImageLimits { vision: VisionProfile, media: List(String), frame_rate: Bool, + clip_budget: Int, + max_clip_bytes: Int, fidelity: Fidelity, ) } @@ -148,7 +158,16 @@ pub const gemini_vision = VisionProfile(GeminiGeometry, False, 200) /// The bounds albedo itself validates images against, for a provider that /// states none of its own. pub const any_images = - ImageLimits(max_image_edge, None, default_vision, [], False, full_fidelity) + ImageLimits( + max_image_edge, + None, + default_vision, + [], + False, + request_clip_budget, + max_clip_bytes, + full_fidelity, + ) /// Anthropic takes an 8000px image alone, but once a request carries more /// than 20 images every one of them, old turns and tool results included, @@ -162,6 +181,8 @@ pub const anthropic_images = vision: anthropic_vision, media: [], frame_rate: False, + clip_budget: request_clip_budget, + max_clip_bytes: max_clip_bytes, fidelity: full_fidelity, ) @@ -201,6 +222,13 @@ pub fn media_refusal(limits: ImageLimits, image: Image) -> Option(String) { case media_kind(image), clip_fps(image), limits.fidelity.max_fps { Picture, _, _ -> image_refusal(limits, image) _, _, _ if !readable -> Some("this model does not read " <> image.mime_type) + _, _, _ if image.bytes > limits.max_clip_bytes -> + Some( + "this model takes clips of at most " + <> mebibytes(limits.max_clip_bytes) + <> ", not " + <> mebibytes(image.bytes), + ) _, None, _ -> None _, Some(_), None -> Some("this model takes no fps for a video") _, Some(fps), Some(most) if fps >. most -> @@ -276,20 +304,24 @@ fn sampled(most: Option(Float), image: Image) -> #(Image, String) { } /// clips are refused on arrival. this trims only a history already over the -/// budget, after a switch to larger copies or originals, or with ffmpeg gone. -pub fn within_clip_budget(inputs: List(Input)) -> List(Input) { +/// budget, after a switch to a smaller one, to larger copies or originals, or +/// with ffmpeg gone. a clip past the per-clip cap goes too. +pub fn within_clip_budget( + inputs: List(Input), + limits: ImageLimits, +) -> List(Input) { inputs |> list.reverse |> list.map_fold(0, fn(spent, input) { case input { UserImage(text, images) -> - case budgeted(spent, images) { + case budgeted(limits, spent, images) { #(spent, _, "") -> #(spent, input) #(spent, [], note) -> #(spent, User(text <> note)) #(spent, kept, note) -> #(spent, UserImage(text <> note, kept)) } ToolOutput(id, output, images) -> - case budgeted(spent, images) { + case budgeted(limits, spent, images) { #(spent, _, "") -> #(spent, input) #(spent, kept, note) -> #(spent, ToolOutput(id, output <> note, kept)) } @@ -300,17 +332,41 @@ pub fn within_clip_budget(inputs: List(Input)) -> List(Input) { |> list.reverse } -fn budgeted(spent: Int, images: List(Image)) -> #(Int, List(Image), String) { - let #(spent, kept, dropped) = - list.fold(list.reverse(images), #(spent, [], 0), fn(acc, image) { - let #(spent, kept, dropped) = acc +fn budgeted( + limits: ImageLimits, + spent: Int, + images: List(Image), +) -> #(Int, List(Image), String) { + let #(spent, kept, large, dropped) = + list.fold(list.reverse(images), #(spent, [], 0, 0), fn(acc, image) { + let #(spent, kept, large, dropped) = acc let size = image_size(image) - case media_kind(image), spent + size <= request_clip_budget { - Picture, _ -> #(spent, [image, ..kept], dropped) - _, True -> #(spent + size, [image, ..kept], dropped) - _, False -> #(spent, kept, dropped + 1) + case media_kind(image) { + Picture -> #(spent, [image, ..kept], large, dropped) + _ if image.bytes > limits.max_clip_bytes -> #( + spent, + kept, + large + 1, + dropped, + ) + _ if spent + size <= limits.clip_budget -> #( + spent + size, + [image, ..kept], + large, + dropped, + ) + _ -> #(spent, kept, large, dropped + 1) } }) + let large_note = case large { + 0 -> "" + _ -> + "\n[" + <> int.to_string(large) + <> " clip(s) omitted: this model takes clips of at most " + <> mebibytes(limits.max_clip_bytes) + <> "]" + } let note = case dropped { 0 -> "" _ -> @@ -318,11 +374,15 @@ fn budgeted(spent: Int, images: List(Image)) -> #(Int, List(Image), String) { <> int.to_string(dropped) <> " clip(s) omitted: newer clips fill this request's media budget]" } - #(spent, kept, note) + #(spent, kept, large_note <> note) } -pub fn clip_budget_refusal(held: Int, adding: Int) -> Option(String) { - case adding > 0 && held + adding > request_clip_budget { +pub fn clip_budget_refusal( + budget: Int, + held: Int, + adding: Int, +) -> Option(String) { + case adding > 0 && held + adding > budget { False -> None True -> Some( @@ -331,7 +391,7 @@ pub fn clip_budget_refusal(held: Int, adding: Int) -> Option(String) { <> ", and the session's clips already hold " <> mebibytes(held) <> " of the " - <> mebibytes(request_clip_budget) + <> mebibytes(budget) <> " one request carries", ) } diff --git a/packages/albedo_model/test/albedo_model/media_budget_test.gleam b/packages/albedo_model/test/albedo_model/media_budget_test.gleam index 8c7a46abd..3b0dc7e62 100644 --- a/packages/albedo_model/test/albedo_model/media_budget_test.gleam +++ b/packages/albedo_model/test/albedo_model/media_budget_test.gleam @@ -28,11 +28,14 @@ pub fn older_clips_past_the_budget_become_a_note_test() -> Nil { types.User(_), types.ToolOutput(_, output, kept), ] = - types.within_clip_budget([ - types.UserImage("first", [clip("a"), picture()]), - types.User("between"), - types.ToolOutput("call", "out", [clip("b"), clip("c")]), - ]) + types.within_clip_budget( + [ + types.UserImage("first", [clip("a"), picture()]), + types.User("between"), + types.ToolOutput("call", "out", [clip("b"), clip("c")]), + ], + types.any_images, + ) assert output == "out" assert list.length(kept) == 2 assert first @@ -42,24 +45,67 @@ pub fn older_clips_past_the_budget_become_a_note_test() -> Nil { pub fn a_message_left_without_images_is_text_test() -> Nil { let assert [types.User(text), _, _] = - types.within_clip_budget([ - types.UserImage("old", [clip("a")]), - types.UserImage("new", [clip("b")]), - types.UserImage("newest", [clip("c")]), - ]) + types.within_clip_budget( + [ + types.UserImage("old", [clip("a")]), + types.UserImage("new", [clip("b")]), + types.UserImage("newest", [clip("c")]), + ], + types.any_images, + ) assert text == "old\n[1 clip(s) omitted: newer clips fill this request's media budget]" } +pub fn a_smaller_wire_budget_keeps_fewer_clips_test() -> Nil { + let limits = + types.ImageLimits( + ..types.any_images, + clip_budget: types.max_clip_encoded_bytes, + ) + let assert [types.User(old), types.User(_), types.UserImage(_, [_])] = + types.within_clip_budget( + [ + types.UserImage("old", [clip("a")]), + types.UserImage("new", [clip("b")]), + types.UserImage("newest", [clip("c")]), + ], + limits, + ) + assert old + == "old\n[1 clip(s) omitted: newer clips fill this request's media budget]" +} + +pub fn a_clip_past_the_wires_cap_is_left_out_test() -> Nil { + let limits = types.ImageLimits(..types.any_images, max_clip_bytes: 20_000_000) + let assert [types.UserImage(text, [kept])] = + types.within_clip_budget( + [types.UserImage("both", [clip("a"), picture()])], + limits, + ) + assert kept == picture() + assert text + == "both\n[1 clip(s) omitted: this model takes clips of at most 19.1 MiB]" + assert types.media_refusal( + types.ImageLimits(..limits, media: ["audio/wav"]), + clip("a"), + ) + == Some("this model takes clips of at most 19.1 MiB, not 20 MiB") +} + pub fn clips_that_fill_the_budget_exactly_fit_test() -> Nil { - assert types.clip_budget_refusal(types.request_clip_budget - 10, 10) == None - assert types.clip_budget_refusal(types.request_clip_budget + 5, 0) == None - let assert Some(reason) = - types.clip_budget_refusal(types.request_clip_budget - 10, 11) + let budget = 12_582_912 + assert types.clip_budget_refusal(budget, budget - 10, 10) == None + assert types.clip_budget_refusal(budget, budget + 5, 0) == None + let assert Some(reason) = types.clip_budget_refusal(budget, budget - 10, 11) assert reason - == "these clips take 0 MiB, and the session's clips already hold 64 MiB of the 64 MiB one request carries" + == "these clips take 0 MiB, and the session's clips already hold 12 MiB of the 12 MiB one request carries" let assert Some(reason) = - types.clip_budget_refusal(40 * 1_048_576, types.max_clip_encoded_bytes) + types.clip_budget_refusal( + types.request_clip_budget, + 40 * 1_048_576, + types.max_clip_encoded_bytes, + ) assert reason == "these clips take 26.7 MiB, and the session's clips already hold 40 MiB of the 64 MiB one request carries" } diff --git a/python/albedo_capture.py b/python/albedo_capture.py index ae782dfe7..cad59fb64 100644 --- a/python/albedo_capture.py +++ b/python/albedo_capture.py @@ -74,6 +74,7 @@ class Capture: media: tuple[str, ...] = (), max_fps: float | None = None, clip_room: int | None = None, + max_clip_bytes: int = MAX_CLIP_BYTES, ) -> None: self.id: str = id self.kind: str = kind @@ -82,6 +83,7 @@ class Capture: self.media: tuple[str, ...] = media self.max_fps: float | None = max_fps self.clip_room: int | None = clip_room + self.max_clip_bytes: int = min(max_clip_bytes, MAX_CLIP_BYTES) self.data: bytearray = bytearray() self._tail: bytearray | None = None self.seen: int = 0 @@ -297,6 +299,13 @@ class Capture: self._check_fps(fps) read = [self._read(data) for data in items] typed = [(data, self._type(data, fps)) for data in read] + for data, mime in typed: + if image_type(data) is None and len(data) > self.max_clip_bytes: + raise ValueError( + f"this {len(data)}-byte {mime} is over the " + f"{self.max_clip_bytes / MIB:.1f} MiB this model takes in one clip; " + "cut or encode it smaller before showing it" + ) for data in read: self._check_shown(data, fps) self._check_room(read) diff --git a/python/albedo_cells.py b/python/albedo_cells.py index b4f86cae4..86c3d9128 100644 --- a/python/albedo_cells.py +++ b/python/albedo_cells.py @@ -9,7 +9,7 @@ import albedo_bundle import albedo_state from albedo_values import Unencodable, decode, encode import albedo_capture -from albedo_capture import Capture, CELL_PREVIEW, PREVIEW +from albedo_capture import Capture, CELL_PREVIEW, MAX_CLIP_BYTES, PREVIEW import albedo_link import albedo_memory import albedo_notices @@ -1474,6 +1474,7 @@ class Cells: media=() if outer is None else outer.media, max_fps=None if outer is None else outer.max_fps, clip_room=None if outer is None else outer.room_left(), + max_clip_bytes=MAX_CLIP_BYTES if outer is None else outer.max_clip_bytes, ) remember(capture) capture.trace.snapshots = outer is not None and outer.trace.snapshots @@ -2763,6 +2764,7 @@ async def serve() -> None: media=tuple(message.get("media", [])), max_fps=message.get("max_fps"), clip_room=message.get("clip_room"), + max_clip_bytes=message.get("max_clip_bytes", MAX_CLIP_BYTES), ) capture.trace.snapshots = message.get("snapshots", False) capture.interruption = "" diff --git a/python/albedo_protocol.py b/python/albedo_protocol.py index 306df1b33..5091f6124 100644 --- a/python/albedo_protocol.py +++ b/python/albedo_protocol.py @@ -34,6 +34,7 @@ class Execute(TypedDict): media: NotRequired[list[str]] max_fps: NotRequired[float | None] clip_room: NotRequired[int] + max_clip_bytes: NotRequired[int] timeout_ms: NotRequired[int] @@ -430,6 +431,7 @@ def parse_incoming(value: object) -> Incoming: "media": "str_list", "max_fps": "float_or_none", "clip_room": "int", + "max_clip_bytes": "int", "timeout_ms": "int", }, ) diff --git a/robot-docs/media.md b/robot-docs/media.md index 6ec0c7d9a..bc14f8383 100644 --- a/robot-docs/media.md +++ b/robot-docs/media.md @@ -36,11 +36,20 @@ read again is matched by `albedo_image.matches` against its first bytes only. A clip holds at most `types.max_clip_bytes` (20 MiB) decoded, a picture `types.max_image_bytes` (5 MiB); `types.max_bytes(mime)` picks the bound, and -validation, uploads and stored rows all read it. A cell attaches at most 4 -pictures and clips together. Its pictures hold 5 MiB together, which keeps the -result inside the kernel link's 8 MiB frame. Each clip may hold 20 MiB and a -cell's clips 40 MiB together, because clips cross the link in raw parts beside -the result (see [Kernel](kernel.md#session-layer)). The kernel's +validation, uploads and stored rows all read it. That is albedo's own ceiling, +for kernel memory, base64 in json, and resends. A wire may declare a lower cap +in `types.ImageLimits.max_clip_bytes` where its provider has one, and the openai +wire does for Azure's 20 MB audio files. The raw upload route cannot know the +model, so it keeps the ceiling, and the wire's cap holds where a message names +the clip or a cell attaches it: `types.media_refusal` refuses a larger clip, the +daemon sends the cap in each `execute` message as `max_clip_bytes`, and +`show_media` raises past it. A request leaves out a clip in its history past the +cap, after its copy is swapped in, with +`[N clip(s) omitted: this model takes clips of at most X MiB]`. A cell attaches +at most 4 pictures and clips together. Its pictures hold 5 MiB together, which +keeps the result inside the kernel link's 8 MiB frame. Each clip may hold 20 MiB +and a cell's clips 40 MiB together, because clips cross the link in raw parts +beside the result (see [Kernel](kernel.md#session-layer)). The kernel's [`clip_type`](../python/albedo_capture.py) ports the Gleam reader so the cell fails at the call. [`clip_header_parity_test`](../apps/albedo/test/albedo/composition/clip_header_parity_test.gleam) @@ -121,10 +130,24 @@ encoders send a tool result's clips in the following user turn, labelled ### The clip budget -A request carries at most `types.request_clip_budget` (64 MiB) of clips as -base64. Antigravity answered a 100 MB request with a 75 MiB WAV inline; no other -wire's ceiling has been measured, so the budget is one constant rather than a -per-wire limit. +A request carries at most `types.ImageLimits.clip_budget` of clips as base64. +Each wire declares its budget beside `max_edge`, leaving the rest of its +provider's request limit, which counts the whole body, to text and pictures. +[`runtime.upstream`](../apps/albedo/src/albedo/runtime.gleam) holds it to +`types.request_clip_budget` (64 MiB), albedo's own ceiling: every turn sends the +whole history's clips again, even where a provider takes far more. Every reader +below takes the budget from the session's limits. A wire that carries no clips +leaves both bounds at albedo's ceilings. + +| Wire | Budget | Source | +| ---------------------------------- | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Vertex | 400 MiB, held to 64 | [500 MiB a request, base64 included](https://docs.cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference) | +| Antigravity's Gemini models | 64 MiB | Measured: a 100 MB request with a 75 MiB WAV inline went through | +| OpenCode Go | 12 MiB | Nothing published. Its edge took 16 MB bodies and refused about 17 MB ([#54784](https://github.com/anomalyco/opencode/issues/54784), [#59067](https://github.com/anomalyco/opencode/issues/59067)) | +| OpenAI-compatible Chat Completions | 64 MiB | Nothing published for `input_audio` | + +The `clip_budget` a `/shake` listing reports is the budget of the session's +current model, or albedo's ceiling when the session has no provider. The budget is kept where clips arrive, so a request never has to leave an older clip out to make room for a newer one. That would change an earlier message and @@ -155,10 +178,10 @@ that would take that past the budget is refused: Inputs already waiting in the queue are not counted, so two messages queued behind a running turn can together pass the budget. -A history can still hold more than the budget: after a switch to a model that is -sent larger copies or the originals, or once ffmpeg is gone. Then -`types.within_clip_budget` keeps a request's clips newest first within it, and -the older ones become +A history can still hold more than the budget: after a switch to a wire with a +smaller budget, or to a model that is sent larger copies or the originals, or +once ffmpeg is gone. Then `types.within_clip_budget` keeps a request's clips +newest first within it, and the older ones become `[N clip(s) omitted: newer clips fill this request's media budget]`. While the history is past the budget every new clip is refused, so each request trims it the same way and its prefix stays cached. `runtime`'s wrapper applies diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index 1a68382ea..0eb97eb20 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -1136,7 +1136,7 @@ export interface paths { }; /** * List the pictures and clips a session's history holds - * @description Each stored picture or clip once, by the first hex digits of its payload hash, with every row that shows it. `clips_held` is the base64 bytes of the clips the session's next request carries, as its model is sent them, which `clip_budget` bounds; null when the session has no provider. + * @description Each stored picture or clip once, by the first hex digits of its payload hash, with every row that shows it. `clips_held` is the base64 bytes of the clips the session's next request carries, as its model is sent them, which `clip_budget` bounds; null when the session has no provider. `clip_budget` is what the wire of the session's current model takes, held to albedo's own 64 MiB, or that ceiling without a provider. */ get: operations["getSessionMedia"]; put?: never;