From 00dfeefcbbef1de126d667f408cbd7aeba80462c Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Wed, 4 Nov 2026 15:29:58 -0500 Subject: [PATCH] providers: clamp the output ceiling to the window, leave OpenRouter its own, resolve Bedrock profile ARNs --- robot-docs/models.md | 12 +- src/albedo/harness/compaction.gleam | 12 ++ src/albedo/harness/extension.gleam | 35 +++- .../bedrock/albedo_bedrock_profiles.erl | 47 ++++++ .../extensions/bedrock/converse_wire.gleam | 5 + .../extensions/bedrock/extension.gleam | 31 ++++ .../harness/extensions/bedrock/profiles.gleam | 150 ++++++++++++++++++ .../harness/extensions/bedrock/sigv4.gleam | 28 +++- .../harness/extensions/openai/extension.gleam | 18 +++ .../harness/extensions/vertex/wire.gleam | 16 +- src/albedo/harness/loop.gleam | 38 +++-- src/albedo/harness/runtime.gleam | 30 ++-- src/albedo/openai_api/types.gleam | 8 +- test/e2e/output_ceiling_test.py | 75 +++++++-- .../harness/bedrock_effort_catalog_test.gleam | 9 +- test/harness/bedrock_test.gleam | 9 +- test/harness/claude_test.gleam | 7 +- test/harness/output_ceiling_test.gleam | 44 +++++ test/harness/vertex_test.gleam | 37 ++++- 19 files changed, 552 insertions(+), 59 deletions(-) create mode 100644 src/albedo/harness/extensions/bedrock/albedo_bedrock_profiles.erl create mode 100644 src/albedo/harness/extensions/bedrock/profiles.gleam create mode 100644 test/harness/output_ceiling_test.gleam diff --git a/robot-docs/models.md b/robot-docs/models.md index dc56c907c..36f174e63 100644 --- a/robot-docs/models.md +++ b/robot-docs/models.md @@ -94,9 +94,17 @@ Provider extensions consume the catalog's endpoint and environment metadata, so ### output ceiling -A request that names no output limit (every turn; the summarizer, warm pings and searches set their own) is sent with the model's catalogued `max_output_tokens`. `runtime.upstream` looks the model up once, with the same `extension.model_info` and endpoint compaction and `/context` use, and wraps the upstream's `stream` to fill the ceiling in before any provider encodes the request, so no provider extension carries a helper for it and a new provider gets it without code. `Upstream.output` records what it chose: `ModelCeiling(tokens, source)`, `NoCeiling`, or `ProviderCeiling`, which a provider declares when its wire refuses the field (Codex: the ChatGPT backend answers `Unsupported parameter: max_output_tokens`, per OpenAI's [Sign in with ChatGPT limitations](https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations)). +A request that names no output limit (every turn; the summarizer, warm pings and searches set their own) is sent with the model's catalogued `max_output_tokens`. `runtime.upstream` looks the model up once, with the same `extension.model_info` and endpoint compaction and `/context` use, and wraps the upstream's `stream` to fill the ceiling in before any provider encodes the request, so no provider extension carries a helper for it and a new provider gets it without code. `Upstream.output` records what it chose: `ModelCeiling(tokens, window, source)`, `NoCeiling`, or `ProviderCeiling`, which a provider declares when the provider must pick its own: the ChatGPT backend answers `Unsupported parameter: max_output_tokens` (OpenAI's [Sign in with ChatGPT limitations](https://developers.openai.com/siwc/token-sharing-open-source/preview-limitations)), and OpenRouter skips every upstream whose cap is below a request's limit, so an `openai` profile at an `openrouter.ai` host is sent only a limit the caller names. -No encoder substitutes a number of its own. A wire where the field is optional (Chat Completions, Responses, Gemini, Bedrock Converse, whose default is the model's maximum per the [InferenceConfiguration reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InferenceConfiguration.html)) omits it when no ceiling is known. Anthropic Messages requires `max_tokens` ([Messages API](https://platform.claude.com/docs/en/api/messages/create)), so both its encoders (`claude/wire`, and `bedrock/wire`, which Copilot and OpenCode Go also use) fail the request through `types.required_output_limit`, naming the model and suggesting `/reload models`, rather than sending a guess. A ceiling at or above the model's largest window is left to the provider: it bounds nothing the window does not, and providers that check prompt plus limit against the window ([vLLM](https://docs.vllm.ai/en/v0.9.0/api/vllm/entrypoints/openai/serving_engine.html), [OpenRouter](https://openrouter.ai/docs/api-reference/parameters)) would refuse every request. A turn that stops on `LengthLimit` says which limit it hit and where it came from (`model stopped: LengthLimit at the 64000-token output limit albedo sent, the model's ceiling from …`), so a wrong catalogue entry reads as one. `test/e2e/output_ceiling_test.py` holds every provider the fake provider can drive to this. +The ceiling is clamped to the room the window leaves (`extension.output_limit`): at most the model's window (default, or its maximum once the cap is raised) less `compaction.request_upper_bound`, the request estimate at three bytes a token plus a 1024-token reserve, and never below 1024 tokens; a prompt that close to the window is compaction's to shrink. Providers that check prompt plus limit against the window refuse anything over it: [vLLM](https://docs.vllm.ai/en/v0.9.0/api/vllm/entrypoints/openai/serving_engine.html), [OpenRouter](https://openrouter.ai/docs/api-reference/parameters), and Anthropic before its 4.5 models ([context windows](https://platform.claude.com/docs/en/build-with-claude/context-windows)). A wire that spends a fixed thinking budget from the same limit (Vertex's Gemini 2.5 `thinkingBudget`) keeps the budget at least 1024 tokens under the limit, never below 128, so a thinking-heavy turn still has room to answer; Antigravity already adds its budget on top of the answer, within the model's limit. + +No encoder substitutes a number of its own. A wire where the field is optional (Chat Completions, Responses, Gemini, Bedrock Converse, whose default is the model's maximum per the [InferenceConfiguration reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InferenceConfiguration.html)) omits it when no ceiling is known. Anthropic Messages requires `max_tokens` ([Messages API](https://platform.claude.com/docs/en/api/messages/create)), so both its encoders (`claude/wire`, and `bedrock/wire`, which Copilot and OpenCode Go also use) fail the request through `types.required_output_limit`, naming the model, that the model list has no output limit for it, and `/reload models`, rather than sending a guess. + +A Bedrock model id that is an ARN is looked up under the model it names: a foundation model ARN's model id, a system inference profile ARN's profile id. An application inference profile ARN names no model, so the Bedrock upstream resolves it once with [GetInferenceProfile](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_GetInferenceProfile.html) on the control plane, with the profile's own credentials (AWS lists `bedrock:GetInferenceProfile` among the [permissions an inference profile needs](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-prereq.html)), and keeps the foundation model it routes to in `$ALBEDO_HOME/bedrock-inference-profiles.json`. A failed resolution is not asked again for ten minutes, and the ARN stays uncatalogued until then. + +The `proxy` extension's clients reach albedo's own profiles, whose models the catalogue describes, so a client request without a limit gets the same ceiling a session would; one with a limit keeps it. + +A turn that stops on `LengthLimit` says which limit it hit and where it came from (`model stopped: LengthLimit at the 64000-token output limit albedo sent, the model's ceiling from …`, or `…, clamped to fit the window: …`), so a wrong catalogue entry or a full window reads as one. `test/e2e/output_ceiling_test.py` holds every provider the fake provider can drive to this; `test/harness/output_ceiling_test.gleam` covers the OpenRouter and Bedrock ARN rules the fake cannot reach. ## provider extensions diff --git a/src/albedo/harness/compaction.gleam b/src/albedo/harness/compaction.gleam index b6e9b20ed..304911d29 100644 --- a/src/albedo/harness/compaction.gleam +++ b/src/albedo/harness/compaction.gleam @@ -808,6 +808,18 @@ pub fn estimate_pinned(instructions: String, tools: List(types.Tool)) -> Int { 16 + estimate_text(instructions) + estimate_tools(tools) } +/// An upper bound on the tokens `request` takes before any output: the +/// estimate at three bytes a token rather than four, plus a reserve for what +/// a provider adds around it (framing, its own system text). +pub fn request_upper_bound(request: types.Request) -> Int { + let estimate = + estimate_pinned(option.unwrap(request.instructions, ""), request.tools) + + estimate_inputs(request.input) + estimate * 4 / 3 + request_reserve +} + +const request_reserve = 1024 + /// Provider tokens per thousand estimated ones: the provider's count for the /// previous request over the estimate of the request now, which differs from /// it only by what arrived since. Byte estimates miss dense tool schemas, diff --git a/src/albedo/harness/extension.gleam b/src/albedo/harness/extension.gleam index 1c8ae393b..07baaeb7b 100644 --- a/src/albedo/harness/extension.gleam +++ b/src/albedo/harness/extension.gleam @@ -296,15 +296,44 @@ pub type Upstream { } pub type OutputCeiling { - /// The model's own output ceiling, and the catalogue that gave it. - ModelCeiling(tokens: Int, source: String) + /// The model's own output ceiling, the window it shares with the prompt + /// when the catalogue knows one, and the catalogue that gave them. + ModelCeiling(tokens: Int, window: Option(Int), source: String) /// No catalogue gives the model a ceiling: a request without a limit goes /// without one, or fails where the wire requires one. NoCeiling - /// The provider refuses an output limit and applies its own. + /// The provider applies its own output limit, so albedo fills none: it + /// refuses the field (the ChatGPT backend), or routes by it (OpenRouter). ProviderCeiling } +/// The output limit a request is sent with, and whether the window clamped it. +pub type OutputLimit { + OutputLimit(tokens: Int, clamped: Bool) +} + +/// The model's ceiling, or less when the window leaves less room after an +/// upper bound on the prompt: providers refuse a prompt plus limit over the +/// window. Never below `output_floor`; a prompt that close to the window is +/// compaction's to shrink. +pub fn output_limit( + tokens: Int, + window: Option(Int), + request: types.Request, +) -> OutputLimit { + let room = case window { + Some(window) -> + int.max(window - compaction.request_upper_bound(request), output_floor) + None -> tokens + } + case room < tokens { + True -> OutputLimit(room, True) + False -> OutputLimit(tokens, False) + } +} + +const output_floor = 1024 + pub type FastMode { FastAvailable(mode: String, source: String) FastUnavailable(reason: String) diff --git a/src/albedo/harness/extensions/bedrock/albedo_bedrock_profiles.erl b/src/albedo/harness/extensions/bedrock/albedo_bedrock_profiles.erl new file mode 100644 index 000000000..82c3cec4b --- /dev/null +++ b/src/albedo/harness/extensions/bedrock/albedo_bedrock_profiles.erl @@ -0,0 +1,47 @@ +-module(albedo_bedrock_profiles). +%% The foundation model each resolved application inference profile ARN +%% invokes, kept in $ALBEDO_HOME/bedrock-inference-profiles.json, and the +%% ARNs whose resolution failed lately, kept in memory. + +-export([saved/2, save/3, recently_failed/1, failed/1]). + +-define(STORE_FILE, "bedrock-inference-profiles.json"). +-define(RETRY_MS, 600000). + +saved(Home, Arn) -> + case maps:get(Arn, read(Home), undefined) of + Model when is_binary(Model), Model =/= <<>> -> {ok, Model}; + _ -> {error, nil} + end. + +save(Home, Arn, Model) -> + Path = path(Home), + Temp = Path ++ ".tmp", + Body = json:encode((read(Home))#{Arn => Model}), + case file:write_file(Temp, Body) of + ok -> _ = file:rename(Temp, Path), nil; + _ -> nil + end. + +recently_failed(Arn) -> + case persistent_term:get({?MODULE, failed, Arn}, undefined) of + At when is_integer(At) -> erlang:monotonic_time(millisecond) - At < ?RETRY_MS; + _ -> false + end. + +failed(Arn) -> + persistent_term:put({?MODULE, failed, Arn}, erlang:monotonic_time(millisecond)), + nil. + +read(Home) -> + case file:read_file(path(Home)) of + {ok, Body} -> + try json:decode(Body) of + Map when is_map(Map) -> Map; + _ -> #{} + catch _:_ -> #{} + end; + _ -> #{} + end. + +path(Home) -> filename:join(unicode:characters_to_list(Home), ?STORE_FILE). diff --git a/src/albedo/harness/extensions/bedrock/converse_wire.gleam b/src/albedo/harness/extensions/bedrock/converse_wire.gleam index e1a0b0fcf..a0214d81a 100644 --- a/src/albedo/harness/extensions/bedrock/converse_wire.gleam +++ b/src/albedo/harness/extensions/bedrock/converse_wire.gleam @@ -120,6 +120,11 @@ pub fn target( } } +/// `text` as one URI-escaped HTTP path segment, ARN slashes included. +pub fn path_segment(text: String) -> String { + encode_segment(bit_array.from_string(text), []) +} + /// Encode the model id as one HTTP path segment, including ARN slashes. pub fn model_path(model: String) -> String { operation_path(model, True) diff --git a/src/albedo/harness/extensions/bedrock/extension.gleam b/src/albedo/harness/extensions/bedrock/extension.gleam index bb41e2641..141ea1238 100644 --- a/src/albedo/harness/extensions/bedrock/extension.gleam +++ b/src/albedo/harness/extensions/bedrock/extension.gleam @@ -16,9 +16,12 @@ import albedo/harness/extensions/bedrock/converse_http import albedo/harness/extensions/bedrock/converse_stream import albedo/harness/extensions/bedrock/converse_wire import albedo/harness/extensions/bedrock/fast +import albedo/harness/extensions/bedrock/profiles import albedo/harness/extensions/bedrock/sigv4 import albedo/harness/extensions/bedrock/wire import albedo/harness/extensions/claude/stream as claude_stream +import albedo/harness/extensions/models/extension as models +import albedo/harness/settings import albedo/openai_api import albedo/openai_api/types import gleam/bool @@ -37,6 +40,11 @@ pub fn extension() -> extension.Extension { "AWS SigV4 or a Bedrock API key for Claude models on Amazon Bedrock (bedrock-runtime or bedrock-mantle)", ["models"], [ + extension.ModelsPlugin(extension.ModelCatalog( + lookup, + fn(_, _) { extension.Unlisted }, + None, + )), extension.ModelProviderPlugin(extension.ModelProvider( "amazon-bedrock", resolve, @@ -47,6 +55,22 @@ pub fn extension() -> extension.Extension { ) } +/// Facts for a model at a Bedrock endpoint, from models.dev's +/// `amazon-bedrock` namespace under the id its ARN names, so an inference +/// profile ARN gets its model's limits. +fn lookup(id: String, at: Option(String)) -> Option(extension.ModelInfo) { + use url <- option.then(at) + use _ <- option.then(wire.target(url) |> option.from_result) + use model <- option.then(profiles.catalogued_id(settings.home(), id)) + use found <- option.map(models.lookup_provider("amazon-bedrock", model)) + extension.ModelInfo( + ..found, + model: id, + provider: "bedrock", + endpoint: Some(url), + ) +} + fn fast_mode(context: extension.ModelContext) -> extension.FastMode { case configuration.settings(context.home, context.profile, config_decoder()) { Error(reason) -> extension.FastUnknown(reason) @@ -78,6 +102,13 @@ fn resolve( aws_profile.region(), )) use _ <- result.try(validate_api(config.api)) + // Resolved before the session's catalogue lookup, which needs its model. + profiles.resolve( + context.home, + context.model, + fn() { authenticate(config) }, + clock.system_seconds(), + ) use _ <- result.try( case config.api { "converse" -> converse_wire.target(base_url) diff --git a/src/albedo/harness/extensions/bedrock/profiles.gleam b/src/albedo/harness/extensions/bedrock/profiles.gleam new file mode 100644 index 000000000..058e9bb75 --- /dev/null +++ b/src/albedo/harness/extensions/bedrock/profiles.gleam @@ -0,0 +1,150 @@ +//// Inference profile ARNs and the catalogued model behind each. A foundation +//// model ARN and a system inference profile ARN name their model; an +//// application inference profile ARN names none, so GetInferenceProfile +//// resolves it once and the answer is kept in +//// `$ALBEDO_HOME/bedrock-inference-profiles.json`. + +import albedo/harness/extensions/bedrock/converse_wire +import albedo/harness/extensions/bedrock/sigv4 +import albedo/harness/extensions/bedrock/wire +import gleam/bit_array +import gleam/bool +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/json +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result +import gleam/string + +/// The id models.dev's `amazon-bedrock` namespace lists `model` under: a +/// foundation model ARN's model, a system inference profile ARN's profile +/// id, the model an application inference profile resolved to, or a plain +/// id as it is. +pub fn catalogued_id(home: String, model: String) -> Option(String) { + case arn(model) { + Error(Nil) -> Some(model) + Ok(Arn(resource: "foundation-model", id:, ..)) + | Ok(Arn(resource: "inference-profile", id:, ..)) -> Some(id) + Ok(Arn(resource: "application-inference-profile", ..)) -> + saved(home, model) |> option.from_result + Ok(_) -> None + } +} + +/// Resolves `model` when it is an application inference profile not yet +/// resolved. AWS requires `bedrock:GetInferenceProfile` to invoke one, so the +/// credentials that invoke it may ask; `auth` is called only then. A failure +/// leaves it unresolved and is not asked again for ten minutes. +pub fn resolve( + home: String, + model: String, + auth: fn() -> Result(wire.Auth, String), + now: Int, +) -> Nil { + case arn(model), saved(home, model) { + Ok(Arn(resource: "application-inference-profile", partition:, region:, ..)), + Error(Nil) + -> { + case recently_failed(model) { + True -> Nil + False -> + case + auth() + |> result.replace_error(Nil) + |> result.try(ask(model, partition, region, _, now)) + { + Ok(id) -> save(home, model, id) + Error(Nil) -> failed(model) + } + } + } + _, _ -> Nil + } +} + +type Arn { + Arn(partition: String, region: String, resource: String, id: String) +} + +fn arn(model: String) -> Result(Arn, Nil) { + case string.split(model, ":") { + ["arn", partition, "bedrock", region, _account, resource, ..version] -> { + use #(kind, id) <- result.try(string.split_once( + string.join([resource, ..version], ":"), + "/", + )) + Ok(Arn(partition, region, kind, id)) + } + _ -> Error(Nil) + } +} + +/// GetInferenceProfile on the control plane, answered with the foundation +/// model its first route invokes. +fn ask( + model: String, + partition: String, + region: String, + auth: wire.Auth, + now: Int, +) -> Result(String, Nil) { + let host = + "bedrock." + <> region + <> case partition { + "aws-cn" -> ".amazonaws.com.cn" + _ -> ".amazonaws.com" + } + let path = "/inference-profiles/" <> converse_wire.path_segment(model) + let headers = case auth { + wire.Bearer(key) -> [#("authorization", "Bearer " <> key)] + wire.SigV4(credentials) -> + sigv4.get_headers_for_path( + credentials, + region, + "bedrock", + host, + now, + path, + ) + } + use #(status, _, body) <- result.try( + http_get("https://" <> host <> path, headers, 10_000, 5000) + |> result.replace_error(Nil), + ) + use <- bool.guard(status != 200, Error(Nil)) + use text <- result.try(bit_array.to_string(body)) + use arns <- result.try( + json.parse( + text, + decode.at(["models"], decode.list(decode.at(["modelArn"], decode.string))), + ) + |> result.replace_error(Nil), + ) + use first <- result.try(list.first(arns)) + case arn(first) { + Ok(Arn(resource: "foundation-model", id:, ..)) -> Ok(id) + _ -> Error(Nil) + } +} + +@external(erlang, "albedo_http", "get") +fn http_get( + url: String, + headers: List(#(String, String)), + timeout: Int, + connect: Int, +) -> Result(#(Int, Dynamic, BitArray), Dynamic) + +@external(erlang, "albedo_bedrock_profiles", "saved") +fn saved(home: String, arn: String) -> Result(String, Nil) + +@external(erlang, "albedo_bedrock_profiles", "save") +fn save(home: String, arn: String, model: String) -> Nil + +@external(erlang, "albedo_bedrock_profiles", "recently_failed") +fn recently_failed(arn: String) -> Bool + +@external(erlang, "albedo_bedrock_profiles", "failed") +fn failed(arn: String) -> Nil diff --git a/src/albedo/harness/extensions/bedrock/sigv4.gleam b/src/albedo/harness/extensions/bedrock/sigv4.gleam index cf9e6b4c0..81a3d94e6 100644 --- a/src/albedo/harness/extensions/bedrock/sigv4.gleam +++ b/src/albedo/harness/extensions/bedrock/sigv4.gleam @@ -82,6 +82,31 @@ pub fn headers_for_path( now: Int, path: String, body: String, +) -> List(#(String, String)) { + sign("POST", creds, region, service, host, now, path, body) +} + +/// `headers_for_path` for a GET, which has no body. +pub fn get_headers_for_path( + creds: Credentials, + region: String, + service: String, + host: String, + now: Int, + path: String, +) -> List(#(String, String)) { + sign("GET", creds, region, service, host, now, path, "") +} + +fn sign( + method: String, + creds: Credentials, + region: String, + service: String, + host: String, + now: Int, + path: String, + body: String, ) -> List(#(String, String)) { let #(amz_datetime, date_stamp) = amz_date(now) let payload_hash = @@ -105,7 +130,8 @@ pub fn headers_for_path( |> list.map(fn(pair) { pair.0 <> ":" <> pair.1 <> "\n" }) |> string.concat let canonical_request = - "POST\n" + method + <> "\n" <> canonical_path(path) <> "\n\n" <> canonical_headers diff --git a/src/albedo/harness/extensions/openai/extension.gleam b/src/albedo/harness/extensions/openai/extension.gleam index 5b1ef5952..207c8087b 100644 --- a/src/albedo/harness/extensions/openai/extension.gleam +++ b/src/albedo/harness/extensions/openai/extension.gleam @@ -12,6 +12,8 @@ import gleam/dynamic/decode import gleam/int import gleam/option.{type Option, None, Some} import gleam/result +import gleam/string +import gleam/uri type Config { Config(image_edge: Int) @@ -105,10 +107,26 @@ fn resolve( int.min(config.image_edge, types.max_image_edge), None, ), + output: output_ceiling(client.base_url), ) }) } +/// OpenRouter skips every upstream whose own cap is below a request's output +/// limit, so a catalogued ceiling it was not asked for narrows the route; it +/// gets only a limit the caller names. +pub fn output_ceiling(base_url: String) -> extension.OutputCeiling { + let host = + uri.parse(base_url) + |> result.map(fn(parsed) { option.unwrap(parsed.host, "") }) + |> result.unwrap("") + |> string.lowercase + case host == "openrouter.ai" || string.ends_with(host, ".openrouter.ai") { + True -> extension.ProviderCeiling + False -> extension.NoCeiling + } +} + fn fast_mode(context: extension.ModelContext) -> extension.FastMode { let pool = pool_mode( diff --git a/src/albedo/harness/extensions/vertex/wire.gleam b/src/albedo/harness/extensions/vertex/wire.gleam index ce30b407f..c717b9d54 100644 --- a/src/albedo/harness/extensions/vertex/wire.gleam +++ b/src/albedo/harness/extensions/vertex/wire.gleam @@ -14,6 +14,7 @@ import albedo/openai_api/types.{ import gleam/bool import gleam/dict.{type Dict} import gleam/dynamic/decode +import gleam/int import gleam/json.{type Json} import gleam/list import gleam/option.{type Option, None, Some} @@ -168,6 +169,7 @@ fn generation_config(request: Request) -> Result(Json, Error) { use thinking <- result.try(thinking_config( request.model, request.options.effort, + request.max_output_tokens, )) let fields = case thinking { [] -> [] @@ -213,6 +215,7 @@ type Thinking { fn thinking_config( model: String, effort: Option(String), + limit: Option(Int), ) -> Result(List(#(String, Json)), Error) { let model = string.lowercase(model) let levels = Levels(["minimal", "low", "medium", "high"]) @@ -265,7 +268,8 @@ fn thinking_config( "high" -> Ok(high) _ -> Error(unsupported) } - result.map(budget, fn(n) { #("thinkingBudget", json.int(n)) }) + use budget <- result.map(budget) + #("thinkingBudget", json.int(answer_room(budget, limit))) } Levels(efforts) -> case list.contains(efforts, effort) { @@ -280,6 +284,16 @@ fn thinking_config( } } +/// A thinking budget that leaves `limit`, which counts thinking too, room for +/// an answer: at most the limit less 1024, though never under the 128 a +/// thinking model needs to think at all. +fn answer_room(budget: Int, limit: Option(Int)) -> Int { + case limit { + Some(limit) -> int.min(budget, int.max(limit - 1024, 128)) + None -> budget + } +} + fn tool_config(tool_choice: Option(types.ToolChoice)) -> Json { let mode = case tool_choice { Some(types.NoTool) -> "NONE" diff --git a/src/albedo/harness/loop.gleam b/src/albedo/harness/loop.gleam index 618c307fa..b29002e0a 100644 --- a/src/albedo/harness/loop.gleam +++ b/src/albedo/harness/loop.gleam @@ -158,25 +158,40 @@ pub type Pin { /// Why a turn ended without finishing, with what it said first. A turn /// names no output limit of its own, so a `LengthLimit` says which one -/// `ceiling` sent and where it came from. +/// `ceiling` gave `request` and where it came from. pub fn stopped_message( finish: types.Finish, output: List(types.ReplayItem), ceiling: extension.OutputCeiling, + request: types.Request, ) -> String { let failure = "model stopped: " <> string.inspect(finish) let failure = case finish, ceiling { - types.LengthLimit, extension.ModelCeiling(tokens, source) -> - failure - <> " at the " - <> int.to_string(tokens) - <> "-token output limit albedo sent, the model's ceiling from " - <> source + types.LengthLimit, extension.ModelCeiling(tokens, window, source) -> + case extension.output_limit(tokens, window, request) { + extension.OutputLimit(sent, False) -> + failure + <> " at the " + <> int.to_string(sent) + <> "-token output limit albedo sent, the model's ceiling from " + <> source + extension.OutputLimit(sent, True) -> + failure + <> " at the " + <> int.to_string(sent) + <> "-token output limit albedo sent, clamped to fit the window: the prompt leaves no more of its " + <> int.to_string(option.unwrap(window, 0)) + <> " tokens; the model's ceiling is " + <> int.to_string(tokens) + <> " from " + <> source + } types.LengthLimit, extension.NoCeiling -> failure <> " at the provider's own output limit: no model catalogue gives this model a ceiling, so albedo sent none" types.LengthLimit, extension.ProviderCeiling -> - failure <> " at the provider's own output limit; this provider takes none" + failure + <> " at the provider's own output limit; albedo sends this provider none" _, _ -> failure } let response = @@ -391,7 +406,12 @@ fn converse( } } _ -> - Error(stopped_message(turn.finish, turn.output, state.upstream.output)) + Error(stopped_message( + turn.finish, + turn.output, + state.upstream.output, + request, + )) } calls -> { use ran <- result.try( diff --git a/src/albedo/harness/runtime.gleam b/src/albedo/harness/runtime.gleam index 303160b53..f37e6225d 100644 --- a/src/albedo/harness/runtime.gleam +++ b/src/albedo/harness/runtime.gleam @@ -1455,34 +1455,34 @@ fn reads_text_only(info: Option(extension.ModelInfo)) -> Bool { /// The model's catalogued output ceiling, filled into every request that /// names no limit, so no wire falls back to a default that is not the -/// model's. A ceiling at or above the model's window bounds nothing the -/// window does not, and a provider that checks prompt plus limit against the -/// window would refuse it, so it is left to the provider. +/// model's; `extension.output_limit` clamps it to the room the window leaves. fn with_output_ceiling( upstream: extension.Upstream, info: Option(extension.ModelInfo), ) -> extension.Upstream { - let ceiling = { - use info <- option.then(info) - use tokens <- option.then(info.max_output_tokens) - case option.or(info.max_context_tokens, info.context_tokens) { - Some(window) if window <= tokens -> None - _ -> Some(#(tokens, catalogued(info))) - } - } - case upstream.output, ceiling { - extension.NoCeiling, Some(#(tokens, source)) -> + case upstream.output, info { + extension.NoCeiling, + Some(extension.ModelInfo(max_output_tokens: Some(tokens), ..) as info) + -> { + let window = selection.raised_window(info) extension.Upstream( ..upstream, - output: extension.ModelCeiling(tokens, source), + output: extension.ModelCeiling(tokens, window, catalogued(info)), stream: fn(request: types.Request, on_event) { let request = case request.max_output_tokens { - None -> types.Request(..request, max_output_tokens: Some(tokens)) + None -> + types.Request( + ..request, + max_output_tokens: Some( + extension.output_limit(tokens, window, request).tokens, + ), + ) Some(_) -> request } upstream.stream(request, on_event) }, ) + } _, _ -> upstream } } diff --git a/src/albedo/openai_api/types.gleam b/src/albedo/openai_api/types.gleam index a094c7d42..ca2c1694f 100644 --- a/src/albedo/openai_api/types.gleam +++ b/src/albedo/openai_api/types.gleam @@ -257,10 +257,10 @@ pub fn required_output_limit( Some(_) -> Error(InvalidRequest("max_output_tokens must be positive")) None -> Error(InvalidRequest( - wire - <> " requires an output limit, and no model catalogue gives " - <> request.model - <> " one; run /reload models, or pick a model the catalogue lists", + request.model + <> " has no output limit in the model list (models.dev, or the provider's own), and " + <> wire + <> " requires one: run /reload models to fetch a list that has it, or pick a model whose entry lists one", )) } } diff --git a/test/e2e/output_ceiling_test.py b/test/e2e/output_ceiling_test.py index 3652781ae..1b6238914 100644 --- a/test/e2e/output_ceiling_test.py +++ b/test/e2e/output_ceiling_test.py @@ -71,6 +71,9 @@ CASES = [ ), ] +# About 20000 tokens at three bytes each, a third of the tight models' window. +LONG_PROMPT = "word " * 12000 + LIMIT_FIELDS = {"max_tokens", "max_completion_tokens", "max_output_tokens"} @@ -91,8 +94,9 @@ MODELS_DEV = { "glm-fixture": limits(200000, 33333), "claude-go-fixture": limits(200000, 44444), "zen-fixture": limits(200000, 55555), - # A ceiling as large as the window bounds nothing. - "wide-model": limits(100000, 100000), + # Ceilings a long prompt leaves no room for. + "tight-chat": limits(60000, 50000), + "claude-tight": limits(60000, 50000), }, }, "mistral": { @@ -158,13 +162,18 @@ def cut_off(_request): @exclusive_class class OutputCeilingTests(unittest.TestCase): def start(self, profiles, script=answer): - """One provider per profile, each `(name, extension, protocol, model)`.""" + """Profiles `(name, extension, protocol, model)`, one fake provider per + extension: OpenCode Go pools its profiles' keys, so two of its profiles + may send to either one's base url.""" + shared = {} providers = {} configured = {} + models = [{"id": model} for *_, model in profiles] for name, extension, protocol, model in profiles: - provider = Provider(script, catalog={"data": [{"id": model}]}) - self.addCleanup(provider.close) - providers[name] = provider + if extension not in shared: + shared[extension] = Provider(script, catalog={"data": models}) + self.addCleanup(shared[extension].close) + provider = providers[name] = shared[extension] configured[name] = { "extension": extension, "baseUrl": provider.url, @@ -185,11 +194,11 @@ class OutputCeilingTests(unittest.TestCase): self.addCleanup(app.__exit__, None, None, None) return app, providers - def turn(self, app, profile): + def turn(self, app, profile, prompt="say ok"): """Runs one turn on `profile` and returns the errors it ended with.""" app.profile = profile session = app.session() - app.prompt(session, "say ok").close() + app.prompt(session, prompt).close() snapshot = app.idle(session) return [ line["text"] @@ -202,9 +211,10 @@ class OutputCeilingTests(unittest.TestCase): for name, _, _, model, field, ceiling in CASES: with self.subTest(provider=name): self.assertEqual(self.turn(app, name), []) - [request] = providers[name].requests + [request] = [ + sent for sent in providers[name].requests if sent["model"] == model + ] body = request["request"] - self.assertEqual(body["model"], model) # Exactly the catalogue's number, in the one field its wire # names: a wire default would be some other number. self.assertEqual(body[field], ceiling) @@ -215,21 +225,22 @@ class OutputCeilingTests(unittest.TestCase): [ ("unknown-chat", "openai", "chat_completions", "unknown-model"), ("unknown-responses", "openai", "responses", "unknown-model"), - ("wide", "openai", "chat_completions", "wide-model"), ] ) - for name, provider in providers.items(): - with self.subTest(provider=name): - self.assertEqual(self.turn(app, name), []) - [request] = provider.requests - self.assertEqual(LIMIT_FIELDS & request["request"].keys(), set()) + for name in providers: + self.assertEqual(self.turn(app, name), []) + requests = providers["unknown-chat"].requests + self.assertEqual(len(requests), 2) + for request in requests: + self.assertEqual(LIMIT_FIELDS & request["request"].keys(), set()) def test_a_wire_that_requires_a_limit_names_the_missing_ceiling(self): app, providers = self.start( [("messages", "opencode-go", "chat_completions", "claude-uncatalogued")] ) [failure] = self.turn(app, "messages") - self.assertIn("Anthropic Messages requires an output limit", failure) + self.assertIn("no output limit in the model list", failure) + self.assertIn("Anthropic Messages requires one", failure) self.assertIn("claude-uncatalogued", failure) # Nothing reached the provider with a number standing in for it. self.assertEqual(providers["messages"].requests, []) @@ -245,6 +256,36 @@ class OutputCeilingTests(unittest.TestCase): ) self.assertIn("models.dev catalog", failure) + def test_a_prompt_near_the_window_clamps_the_limit_to_fit_it(self): + app, providers = self.start( + [ + ("chat", "openai", "chat_completions", "tight-chat"), + ("messages", "opencode-go", "chat_completions", "claude-tight"), + ] + ) + for name, field in ( + ("chat", "max_completion_tokens"), + ("messages", "max_tokens"), + ): + with self.subTest(provider=name): + self.assertEqual(self.turn(app, name, LONG_PROMPT), []) + [request] = providers[name].requests + sent = request["request"][field] + # Under the 50000 ceiling, and with the prompt (at a + # conservative three bytes a token) still inside the 60000 + # window; never below the floor. + self.assertLess(sent, 50000) + self.assertLessEqual(sent, 60000 - len(LONG_PROMPT) // 3) + self.assertGreaterEqual(sent, 1024) + + def test_a_clamped_turn_cut_off_at_its_limit_says_it_was_clamped(self): + app, _ = self.start( + [("chat", "openai", "chat_completions", "tight-chat")], script=cut_off + ) + failure = self.turn(app, "chat", LONG_PROMPT)[0] + self.assertIn("clamped to fit the window", failure) + self.assertIn("the model's ceiling is 50000", failure) + if __name__ == "__main__": unittest.main() diff --git a/test/harness/bedrock_effort_catalog_test.gleam b/test/harness/bedrock_effort_catalog_test.gleam index f01cecc63..50502a2f2 100644 --- a/test/harness/bedrock_effort_catalog_test.gleam +++ b/test/harness/bedrock_effort_catalog_test.gleam @@ -168,8 +168,13 @@ fn unwrap_extensions( } fn upstream(home: String, profile: String) -> harness.Upstream { - let assert [harness.ModelProviderPlugin(provider)] = - bedrock.extension().plugins + let assert Ok(provider) = + list.find_map(bedrock.extension().plugins, fn(plugin) { + case plugin { + harness.ModelProviderPlugin(provider) -> Ok(provider) + _ -> Error(Nil) + } + }) let assert Some(Ok(upstream)) = provider.resolve(harness.ModelContext( home, diff --git a/test/harness/bedrock_test.gleam b/test/harness/bedrock_test.gleam index 626a27960..28891364d 100644 --- a/test/harness/bedrock_test.gleam +++ b/test/harness/bedrock_test.gleam @@ -510,8 +510,13 @@ pub fn reused_upstream_refreshes( home: String, remove_credentials: fn() -> Nil, ) -> Nil { - let assert [harness_extension.ModelProviderPlugin(provider)] = - extension.extension().plugins + let assert Ok(provider) = + list.find_map(extension.extension().plugins, fn(plugin) { + case plugin { + harness_extension.ModelProviderPlugin(provider) -> Ok(provider) + _ -> Error(Nil) + } + }) let assert Some(Ok(upstream)) = provider.resolve(harness_extension.ModelContext( home, diff --git a/test/harness/claude_test.gleam b/test/harness/claude_test.gleam index ec94e102c..f64d4cd04 100644 --- a/test/harness/claude_test.gleam +++ b/test/harness/claude_test.gleam @@ -466,7 +466,12 @@ pub fn claude_refusal_details_and_text_reach_failure_message_test() -> Nil { "{\"type\":\"message_stop\"}", ]) let failure = - loop.stopped_message(turn.finish, turn.output, extension.NoCeiling) + loop.stopped_message( + turn.finish, + turn.output, + extension.NoCeiling, + types.Request("claude-opus-5-5", None, [], [], None, types.defaults), + ) assert string.contains(failure, "refusal (policy): private credentials") assert string.contains(failure, "I can’t help with that request.") } diff --git a/test/harness/output_ceiling_test.gleam b/test/harness/output_ceiling_test.gleam new file mode 100644 index 000000000..9a97a30a4 --- /dev/null +++ b/test/harness/output_ceiling_test.gleam @@ -0,0 +1,44 @@ +//// Provider facts about output limits that the e2e fake cannot reach: it +//// serves loopback only, so neither an OpenRouter host nor a Bedrock ARN's +//// model can be put in front of it. + +import albedo/harness/extension +import albedo/harness/extensions/bedrock/profiles +import albedo/harness/extensions/openai/extension as openai +import gleam/option.{None, Some} + +/// OpenRouter skips routes whose cap is below a request's limit, so it is +/// sent none it was not asked for; every other endpoint gets the ceiling. +pub fn only_openrouter_is_left_its_own_output_limit_test() -> Nil { + assert openai.output_ceiling("https://openrouter.ai/api/v1") + == extension.ProviderCeiling + assert openai.output_ceiling("https://eu.OpenRouter.ai/api/v1") + == extension.ProviderCeiling + assert openai.output_ceiling("https://api.openai.com/v1") + == extension.NoCeiling + assert openai.output_ceiling("https://openrouter.ai.example/v1") + == extension.NoCeiling +} + +/// An inference profile ARN that names its model is looked up under that +/// model; an application profile no one resolved names nothing yet. +pub fn a_bedrock_arn_is_catalogued_under_the_model_it_names_test() -> Nil { + let home = "/nonexistent" + assert profiles.catalogued_id(home, "us.anthropic.claude-sonnet-5-5") + == Some("us.anthropic.claude-sonnet-5-5") + assert profiles.catalogued_id( + home, + "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-sonnet-5-5", + ) + == Some("anthropic.claude-sonnet-5-5") + assert profiles.catalogued_id( + home, + "arn:aws:bedrock:us-east-1:111122223333:inference-profile/us.anthropic.claude-sonnet-5-5", + ) + == Some("us.anthropic.claude-sonnet-5-5") + assert profiles.catalogued_id( + home, + "arn:aws:bedrock:us-east-1:111122223333:application-inference-profile/abc123", + ) + == None +} diff --git a/test/harness/vertex_test.gleam b/test/harness/vertex_test.gleam index 586a769bd..f2570602d 100644 --- a/test/harness/vertex_test.gleam +++ b/test/harness/vertex_test.gleam @@ -359,7 +359,13 @@ pub fn effort_uses_budgets_for_25_and_levels_for_3_test() -> Nil { #("gemini-2.5-flash-lite", "minimal", 0), ], fn(case_) { - let value = encoded(with_effort(case_.0, case_.1)) + let value = + encoded( + types.Request( + ..with_effort(case_.0, case_.1), + max_output_tokens: Some(65_536), + ), + ) assert at( value, ["generationConfig", "thinkingConfig", "thinkingBudget"], @@ -367,7 +373,7 @@ pub fn effort_uses_budgets_for_25_and_levels_for_3_test() -> Nil { ) == case_.2 assert at(value, ["generationConfig", "maxOutputTokens"], decode.int) - == 100 + == 65_536 }, ) list.each( @@ -392,6 +398,33 @@ pub fn effort_uses_budgets_for_25_and_levels_for_3_test() -> Nil { ) } +/// Thinking counts against `maxOutputTokens`, so a budget at or above a +/// clamped limit would leave a thinking-heavy turn no answer. +pub fn a_thinking_budget_leaves_the_limit_room_for_an_answer_test() -> Nil { + list.each( + [ + #("gemini-2.5-pro", "high", 4096, 3072), + #("gemini-2.5-pro", "low", 1024, 128), + #("gemini-2.5-flash", "minimal", 1024, 0), + ], + fn(case_) { + let value = + encoded( + types.Request( + ..with_effort(case_.0, case_.1), + max_output_tokens: Some(case_.2), + ), + ) + assert at( + value, + ["generationConfig", "thinkingConfig", "thinkingBudget"], + decode.int, + ) + == case_.3 + }, + ) +} + pub fn unsupported_effort_is_not_silently_ignored_test() -> Nil { list.each( [ -- knotmirror 0.0.1