Context Budgets and Structured Trace Events for Multi-Step Agents
Long-running agents in production hit two hard ceilings: context windows fill up with old steps and failures become impossible to trace. This design shows a concrete, low-dependency pattern for enforcing a run-level character budget and emitting privacy-safe JSON events that map failures to specific steps, useful for any team building multi-step tool-calling agents.
The design fixes two problems that plague long-running agents: unbounded context growth and invisible execution traces. Context management now has three layers: session-level summaries plus recent 50 messages, run-level budgets that keep only the most recent 8 ActionSteps and drop whole older steps under a 32,000-character cap, and message-level truncation for individual tool and code observations. Dropping whole steps matters because splitting a tool_call from its response breaks OpenAI's API contract.
Observability moves beyond a single aggregated [META] metric to structured JSON events. A `agent.trace` logger emits `run_start`, `llm_end`, `tool_start`, `tool_error`, `stream_step`, `step_end`, `max_steps_reached`, `run_error`, and `run_finish` events, each with timing, token counts, and context stats. The traces deliberately exclude raw user messages, model outputs, tool arguments, and code bodies, preserving a privacy boundary while still letting developers pinpoint failures by step.
The build borrows the step-memory pattern from smolagents but adds its own character-budget logic and deduplicated trace pipeline. The author evaluated Langfuse and decided against integration for now, keeping local MySQL telemetry as the sink. Known limitations include character counts being an approximation of token counts, deterministic step dropping without semantic summarization, and no replay capability for dropped steps.
Character budgets are a pragmatic stopgap, but they will diverge from token counts on Chinese and code-heavy workloads, so teams should expect drift and either accept it or tokenize precisely.
Deterministically dropping whole old steps sacrifices semantic continuity in favor of contract safety; using an LLM to summarize old steps would add cost and latency that this design deliberately avoids.
The privacy boundary in trace logs is unusually strict: excluding tool arguments and code bodies makes debugging harder but sidesteps the data-handling concerns that block logging in many enterprises.
Deferring Langfuse in favor of a local MySQL sink keeps the stack lightweight, but it also means no distributed tracing or external replay capabilities, which could become a bottleneck as agent runs grow more complex.
That hits the spot. The detail of discarding whole steps while preserving tool_call pairing shows real craftsmanship. Logging only lengths and not content—I'd like to borrow that privacy boundary too.
Clever