跪拜 Guibai
← All articles
Backend · Agent

Context Budgets and Structured Trace Events for Multi-Step Agents

By CRZZX ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

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.

Summary

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.

Takeaways
— Context is managed in three layers: session summaries plus recent 50 messages, run-level budget keeping recent 8 ActionSteps under a 32,000-character cap, and per-message truncation with a 6,000-character limit.
— Dropping an entire ActionStep keeps the pairing between assistant tool_calls and their responses intact; deleting only the tool response triggers an OpenAI error.
— A `[上下文压缩]` hint is inserted into the prompt to inform the model how many steps were omitted.
— The character budget is an approximation, not a token count; different tokenizers split Chinese, code, and JSON unevenly.
— The `agent.trace` logger emits 9 structured JSON events covering run start, LLM end, tool start/error, stream steps, step end, max steps, run error, and run finish.
— Trace logs record lengths, counts, metrics, names, and error types, but never raw user messages, model outputs, tool arguments, or code bodies.
— The implementation mirrors smolagents' `AgentMemory`, `write_memory_to_messages()`, `truncate_content()`, `Timing`, `TokenUsage`, and `Monitor.update_metrics()`, but adds character budget and JSON trace events.
— Langfuse integration was evaluated and postponed; the local admin dashboard already covers current needs, and self-hosting would require Postgres, ClickHouse, Redis, and object storage.
— Three new tests cover omission of old steps, no compaction without a budget, and the structured trace events being JSON and content-free.
Conclusions

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.

Concepts & terms
ActionStep
A unit of memory in a multi-step agent that records one assistant action, including tool calls and their observations, kept as a self-contained block so that tool_call/response pairs stay intact.
Context compression (上下文压缩)
A hint inserted into the prompt after old steps are dropped, telling the model how many execution steps were omitted to maintain a character budget.
agent.trace
A structured JSON logger that emits per-run, per-step, per-LLM-call, and per-tool events for observability, excluding raw content to preserve privacy.
From the discussion
Featured comments
去吧波波鸟

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.

CRZZX

Clever

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗