mirror of
https://github.com/tiennm99/goclaw.git
synced 2026-10-12 18:16:09 +00:00
read_video called with a url parameter always failed under an agent budget:
tool:read_video: cannot verify streamed native media against the agent
context budget (no in-memory payload to count); refusing to send
read_audio and read_document appeared to work but only for very small files.
Both symptoms share one root cause.
5ca433b8 introduced the complete-input invariant and, to keep out-of-band
media honest, appended the standard-base64 encoding of the payload as a
synthetic guard-only message. That message is counted as text. Measured against
the bundled BudgetCounter, base64 costs 0.956 tokens per raw byte, so an 11.6 MB
video counted 11,161,058 tokens and exceeded a 200k, a 1M and a 2M window alike.
The practical ceiling was roughly 200 KB at a 200k window while videoMaxBytes is
100 MB. The read_video URL transport streams to the File API without buffering,
so it had no bytes to count at all and was routed to a helper that refused to
send whenever an agent budget was present.
Media is now priced by what a provider actually bills for it. Every number below
is either a published per-unit rate or a published provider limit; none is
derived from a byte size, because a static-image video compresses arbitrarily
small and no bitrate floor exists. An earlier revision of this branch tried one
and a 120-second, 20,627-byte clip priced at 526 tokens against a true 31,560.
internal/mediabudget prices one payload:
- Video and audio: ffprobe measures duration. 263 tokens/second for video,
32 for audio, both published for static processing at 1 FPS.
- PDF: pdfinfo counts pages at 258 tokens/page. When the page count cannot be
read, the charge is the proven ceiling of 1000 pages, which is the most a
provider will accept and therefore the most it can bill.
- Video and audio that cannot be measured are refused. Upstream already
refused unverifiable native media for every URL on the Gemini streamed path;
this narrows that refusal from every URL to only what genuinely cannot be
measured, rather than removing it. PDF differs because its page count is
cheaply measurable and its ceiling is small enough to stay usable.
A remote video is measured without downloading it: two ranged GETs, 512 KB from
the head and 512 KB from the tail, written into a sparse temp file sized to the
declared total and handed to ffprobe. The tail matters because every container
that puts its index at the end keeps it there: head-only probing under-reports
mpeg by 98% and ogg by 79%, and a plain prefix makes ffprobe under-report a
30-second WAV as 0.74 seconds because it clamps to the bytes it can see. Sizing
the temp file to the real total fixes that. Verified end to end on an 11,673,105
byte MP4 served by nginx: 1 MB of ranged reads yielded duration 40.000000,
identical to ffprobe reading the whole URL, for a charge of 10,520 tokens. Those
requests reuse the existing SSRF-safe path, security.WithPinnedIP plus
security.NewSafeClient(0), and no URL is ever handed to an external binary.
Beyond the reported bug, two pre-existing gaps let large media reach a provider
almost unpriced. ExecuteWithChain treated every callProvider error as a provider
failure and advanced to the next entry, and the non-Gemini branches of read_video
and read_document reserved without pricing their payload at all. Measured under a
20,000-token window before this change, a 40 MB video and a 1000-page PDF each
reached a provider charged about 1,600 tokens. Budget refusals are now terminal
in the chain and every media branch prices its payload, so both reach no provider
at all. Genuine provider failures still fail over.
Known limits, stated rather than discovered:
- The /Type /Page scan that guards against a forged /Count is a floor, not a
bound. Pages inside a compressed object stream are invisible to it, and a
9,484-byte PDF built that way is charged 258 tokens for 1000 pages. A real
pdfinfo reads such files correctly; the scan only ever raises a probed count.
- A video URL whose origin does not serve byte ranges is now refused on the
non-Gemini path too, and the refusal is terminal. Upstream forwarded such URLs
unpriced. A HEAD giving only a size is not enough to price one.
- read_video and read_audio require ffprobe. Docker images install it by default
except the base variant; bare binaries and the desktop build do not ship it.
- A hostile origin can craft a container ffprobe reads as about one second.
Reservation.Reconcile overwrites the estimate with the provider's reported
usage, so this weakens the gate rather than defeating it.
Byte ceilings videoMaxBytes, audioMaxBytes and documentMaxBytes are unchanged.
No new module dependency; ffprobe and pdfinfo are optional runtime probes.
164 lines
6.1 KiB
Go
164 lines
6.1 KiB
Go
package tools
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/nextlevelbuilder/goclaw/internal/mediabudget"
|
|
"github.com/nextlevelbuilder/goclaw/internal/providers"
|
|
"github.com/nextlevelbuilder/goclaw/internal/store"
|
|
usagecaps "github.com/nextlevelbuilder/goclaw/internal/usage/caps"
|
|
)
|
|
|
|
// budgetRefusalError marks a denial that came from the budget, not from a
|
|
// provider being unwell. A media fallback chain must stop on one: trying the
|
|
// next provider only moves the same payload to another endpoint, and the next
|
|
// entry may not price media at all.
|
|
type budgetRefusalError struct{ err error }
|
|
|
|
func (e *budgetRefusalError) Error() string { return e.err.Error() }
|
|
func (e *budgetRefusalError) Unwrap() error { return e.err }
|
|
|
|
// asBudgetRefusal marks err when it is one of the budget denials, and returns
|
|
// it untouched otherwise. Every gate on the media path funnels through here:
|
|
// the unmeasurable-media refusal, the agent context window, the missing-budget
|
|
// wiring failure, and the tenant usage cap.
|
|
func asBudgetRefusal(err error) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var windowErr *usagecaps.ContextWindowExceededError
|
|
var wiringErr *usagecaps.AgentBudgetWiringError
|
|
switch {
|
|
case errors.Is(err, mediabudget.ErrDurationUnmeasurable),
|
|
errors.Is(err, usagecaps.ErrCapExceeded),
|
|
errors.As(err, &windowErr),
|
|
errors.As(err, &wiringErr):
|
|
return &budgetRefusalError{err: err}
|
|
default:
|
|
return err
|
|
}
|
|
}
|
|
|
|
// isBudgetRefusal reports whether err is a budget denial, however deeply it has
|
|
// been wrapped on its way back up.
|
|
func isBudgetRefusal(err error) bool {
|
|
var refusal *budgetRefusalError
|
|
return errors.As(err, &refusal)
|
|
}
|
|
|
|
func agentBudgetFromContext(ctx context.Context) usagecaps.AgentBudget {
|
|
return usagecaps.AgentBudget{
|
|
ContextWindow: store.AgentContextWindowFromContext(ctx),
|
|
MaxTokens: store.AgentMaxTokensFromContext(ctx),
|
|
}
|
|
}
|
|
|
|
// reserveToolLLMUsage guards and reserves a tool-internal model call whose full
|
|
// input already lives in the ChatRequest. The fixed local BudgetCounter counts
|
|
// the request itself.
|
|
func reserveToolLLMUsage(ctx context.Context, svc *usagecaps.Service, toolName, providerName, model string, req providers.ChatRequest) (*usagecaps.Reservation, error) {
|
|
return reserveToolLLMUsageWithMediaTokens(ctx, svc, toolName, providerName, model, req, 0)
|
|
}
|
|
|
|
// reserveToolLLMUsageWithMedia guards a native-media tool call whose payload is
|
|
// sent OUT-OF-BAND (native provider JSON body or File API upload) and is thus
|
|
// invisible to the ChatRequest the counter would otherwise see. A payload
|
|
// mediabudget cannot price aborts the call rather than being waved through at
|
|
// an invented number.
|
|
func reserveToolLLMUsageWithMedia(ctx context.Context, svc *usagecaps.Service, toolName, providerName, model string, req providers.ChatRequest, media ...mediabudget.Payload) (*usagecaps.Reservation, error) {
|
|
mediaTokens := 0
|
|
for _, p := range media {
|
|
tokens, err := mediabudget.Tokens(ctx, p)
|
|
if err != nil {
|
|
return nil, asBudgetRefusal(err)
|
|
}
|
|
mediaTokens += tokens
|
|
}
|
|
return reserveToolLLMUsageWithMediaTokens(ctx, svc, toolName, providerName, model, req, mediaTokens)
|
|
}
|
|
|
|
// refuseUnpriceableMedia is the front gate for a payload whose cost cannot be
|
|
// established at all, used where there is not even a Payload to hand to
|
|
// mediabudget. It carries the same terminal marker as a priced refusal.
|
|
func refuseUnpriceableMedia(kind mediabudget.Kind, cause error) error {
|
|
return asBudgetRefusal(fmt.Errorf("%s budget: %w", kind, cause))
|
|
}
|
|
|
|
// reserveToolLLMUsageWithMediaTokens is the shared path for a media charge that is already a token count, not a mediabudget.Payload.
|
|
func reserveToolLLMUsageWithMediaTokens(ctx context.Context, svc *usagecaps.Service, toolName, providerName, model string, req providers.ChatRequest, mediaTokens int) (*usagecaps.Reservation, error) {
|
|
budget := agentBudgetFromContext(ctx)
|
|
req = clampToolRequestMaxTokens(req, budget.MaxTokens)
|
|
if guardErr := usagecaps.GuardContextWindowWithMediaTokens(req, providerName, model, "tool:"+toolName, budget, mediaTokens); guardErr != nil {
|
|
return nil, asBudgetRefusal(guardErr)
|
|
}
|
|
if svc == nil {
|
|
return nil, nil
|
|
}
|
|
reservation, err := svc.Preflight(ctx, usagecaps.Request{
|
|
TenantID: store.TenantIDFromContext(ctx),
|
|
AgentID: store.AgentIDFromContext(ctx),
|
|
ProviderName: providerName,
|
|
ModelID: model,
|
|
ReservationKey: fmt.Sprintf("tool:%s:%s", toolName, uuid.NewString()),
|
|
Messages: req.Messages,
|
|
MaxOutputTokens: budget.MaxTokens,
|
|
ExtraInputTokens: mediaTokens,
|
|
})
|
|
return reservation, asBudgetRefusal(err)
|
|
}
|
|
|
|
// clampToolRequestMaxTokens enforces max_tokens <= agentMaxTokens for every
|
|
// agent-originated tool call. A request that does not declare max_tokens is set
|
|
// to the agent's max_tokens rather than left to a provider default, so the
|
|
// window invariant (completeInput + agentMaxTokens <= window) holds for the
|
|
// value actually sent.
|
|
func clampToolRequestMaxTokens(req providers.ChatRequest, agentMaxTokens int) providers.ChatRequest {
|
|
if agentMaxTokens <= 0 {
|
|
return req
|
|
}
|
|
if req.Options == nil {
|
|
req.Options = map[string]any{}
|
|
}
|
|
current, ok := maxOutputTokensDeclared(req.Options)
|
|
if !ok || current > agentMaxTokens {
|
|
req.Options[providers.OptMaxTokens] = agentMaxTokens
|
|
}
|
|
return req
|
|
}
|
|
|
|
// maxOutputTokensDeclared reports the max_tokens declared in the request options
|
|
// and whether it was present at all. The bool distinguishes a genuinely missing
|
|
// option (ok == false) from an explicit zero, which the clamp needs so it can
|
|
// set the agent's max_tokens when the caller declared nothing.
|
|
func maxOutputTokensDeclared(options map[string]any) (int, bool) {
|
|
if options == nil {
|
|
return 0, false
|
|
}
|
|
v, ok := options[providers.OptMaxTokens]
|
|
if !ok {
|
|
return 0, false
|
|
}
|
|
switch n := v.(type) {
|
|
case int:
|
|
return n, true
|
|
case int64:
|
|
return int(n), true
|
|
case int32:
|
|
return int(n), true
|
|
case float64:
|
|
return int(n), true
|
|
case float32:
|
|
return int(n), true
|
|
default:
|
|
return 0, false
|
|
}
|
|
}
|
|
|
|
func maxOutputTokensFromOptions(options map[string]any) int {
|
|
maxTokens, _ := maxOutputTokensDeclared(options)
|
|
return maxTokens
|
|
}
|