Context Budgets and Structured Trace Events for Multi-Step Agents
Agent Context Management and Observability Design
1. Conclusion First
The current code already borrows part of the context and observability design from smolagents:
AgentMemory/TaskStep/ActionStepstep-based memory;- Rebuilding messages at each step;
- Truncation of tool observations and code output;
Timing,TokenUsage,[META]statistics;- ReAct LangChain callback metrics.
But two pieces are still missing:
- Context budget for a single Agent run: previously each step replayed all historical steps, so long tasks would grow without bound;
- Structured observability logs: previously there were
[META]and ordinary logs, but no stable JSON events, making it impossible to track a run by step / LLM / tool.
This round has added them:
Context Management
├─ Session level: chat_summaries + recent messages (already present)
├─ Run level: keep recent N ActionSteps + character budget (new)
└─ Message level: truncate individual tool/code Observations (already present + new unified entry)
Observability
├─ Run level: [META] SSE statistics (already present)
├─ Step level: agent.trace JSON events (new)
├─ Model level: llm_end events (new)
└─ Tool level: tool_start / tool_error events (new)
2. Context Management Strategy
2.1 Three-Layer Context
User Request
│
▼
Layer 1: Session Context
├─ chat_summaries summary
└─ recent 50 messages
│
▼
Layer 2: Current Run Context
├─ system prompt
├─ current task
├─ recent N ActionSteps
└─ hint for omitted steps
│
▼
Layer 3: Single Message
├─ Tool Observation truncation
├─ CodeAgent print / output truncation
└─ Overlong messages truncated by character cap
│
▼
Model Request
2.2 Session Level: Existing Summary + Recent Messages
Location:
zzx-ai-agent-backend/app/chat_history.pybuild_context()load_summary()load_recent_messages()update_summary()
Strategy:
- Keep conversation summary;
- Keep recent 50 messages;
- Update summary every 5 turns or when accumulated characters exceed a threshold.
This layer handles long-term memory across turns of dialogue, which is a different context from the ReAct memory within a single Agent run.
2.3 Run Level: AgentMemory Character Budget
Location:
zzx-ai-agent-backend/app/agent_core/memory.py→AgentMemory.to_messages()zzx-ai-agent-backend/app/agent_core/agents.py→MultiStepAgent.write_memory_to_messages()
Core strategy:
- Always keep the system prompt and TaskStep;
- Only look at the most recent
MULTISTEP_CONTEXT_KEEP_STEPSActionSteps; - Discard earlier ActionSteps as whole steps, without splitting the assistant tool_call and tool response;
- After discarding, insert a
[上下文压缩](context compression) hint to tell the model how many steps were omitted; - Truncate a single message when it exceeds
MULTISTEP_CONTEXT_MESSAGE_CHARS; - If total characters still exceed
MULTISTEP_CONTEXT_MAX_CHARS, continue dropping the oldest steps until under budget or only 1 step remains.
system prompt
│
▼
TaskStep
│
▼
[上下文压缩] Omitted N execution steps
│
▼
Recent 8 ActionSteps
│
▼
Next model request
Why "whole-step dropping":
- In ToolCallingAgent, the assistant message contains
tool_calls; - The corresponding tool response must exist in the same history;
- If only the tool response is removed, OpenAI reports "tool_call has no corresponding result";
- Deleting the entire ActionStep keeps the pairing intact.
2.4 Message Level: Observation and Code Output Truncation
Already present:
app/agent_core/utils.py→truncate_content();ToolSpec/ToolCallingAgentusecompact_text();CodeAgentusestruncate_content()forprint()and execution results;MULTISTEP_MAX_OUTPUT_CHARScontrols the length of a single Python output;MULTISTEP_MAX_CODE_CHARScontrols the code display length sent to the frontend.
Newly added:
MULTISTEP_CONTEXT_MESSAGE_CHARSas a unified message-level cap;- Final fallback truncation in
AgentMemory.to_messages().
2.5 Configuration Items
MULTISTEP_CONTEXT_MAX_CHARS=32000
MULTISTEP_CONTEXT_KEEP_STEPS=8
MULTISTEP_CONTEXT_MESSAGE_CHARS=6000
| Config | Purpose |
|---|---|
MULTISTEP_CONTEXT_MAX_CHARS |
Total character budget for messages in one model request, approximating a token budget |
MULTISTEP_CONTEXT_KEEP_STEPS |
How many recent ActionSteps to keep at minimum |
MULTISTEP_CONTEXT_MESSAGE_CHARS |
Character cap for a single tool/code Observation |
The character budget is an approximation, not an exact token count. Different model tokenizers split Chinese, code, and JSON differently; precise control requires integrating the corresponding tokenizer.
2.6 ReAct Context
LangChain ReAct still manages its own scratchpad via AgentExecutor. The project provides an outer layer:
chat_history.build_context()for summary + recent messages;stream_agent()for[META]andagent.tracelogs.
This round did not apply a character budget to the ReAct scratchpad, because LangChain's ReAct templates and message history are maintained internally by the framework, and forcibly trimming can break the Action/Observation format. If strict control is needed later, custom message-trimming logic can be added to AgentExecutor.
3. Observability Design
3.1 Three-Layer Observability
Layer 1: Frontend
└─ [META] → steps / tool_calls / tokens / time
Layer 2: SSE Events
├─ [THINK]
├─ [CODE]
├─ [STEP]
├─ [OBSERVE]
├─ [FINAL]
└─ [META]
Layer 3: Server-side JSON Logs
└─ logger = agent.trace
├─ run_start
├─ llm_end
├─ tool_start
├─ tool_error
├─ stream_step
├─ step_end
├─ max_steps_reached
├─ run_error
└─ run_finish
3.2 Event Fields
All agent.trace logs are one JSON per line:
{
"ts": "2026-11-24T02:16:11.907271+00:00",
"event": "step_end",
"engine": "code",
"session_id": "8f2c...",
"request_id": "7f1a...",
"step": 2,
"duration_ms": 842,
"llm_calls": 1,
"prompt_tokens": 1437,
"completion_tokens": 174,
"tool_calls": 1,
"tool_errors": 0,
"error_type": null,
"context": {
"messages": 8,
"chars": 6320,
"action_steps": 3,
"kept_steps": 3,
"omitted_steps": 0,
"truncated_messages": 0,
"max_chars": 32000
}
}
Event descriptions:
| Event | Timing | Key fields |
|---|---|---|
run_start |
When an Agent run starts | max_steps, task_chars, tools |
llm_end |
When each model call ends | call, prompt_tokens, completion_tokens, cumulative values |
tool_start |
When a top-level tool starts | tool |
tool_error |
When a top-level tool fails | tool, error_type |
stream_step |
Each ReAct stream event | step, actions, observations, has_output |
step_end |
When each MultiStepAgent step ends | step, duration_ms, token/tool deltas, context stats |
max_steps_reached |
When max steps is reached | max_steps |
run_error |
When run throws exception | error_type, elapsed_ms |
run_finish |
When run finishes normally | total tokens, steps, tool count, duration, context stats |
3.3 Privacy Boundary
Logs only record:
- Lengths:
task_chars,output_chars; - Counts:
tools,observations; - Metrics: tokens, duration, steps;
- Names: tool names, engine names;
- Error types:
error_type.
Logs do NOT record:
- Raw user messages;
- Raw model output;
- Tool arguments;
- Tool return content;
- Code bodies.
The admin Telemetry table additionally stores raw questions and final answers for the observability dashboard review; they do not go into
agent.tracelogs, nor are they part of the general trace payload. See: Agent Telemetry Dashboard Design.
This allows troubleshooting without writing business data into logs.
3.4 Code Locations
| Focus | File | Function/Location |
|---|---|---|
| Trace class and JSON logs | app/agent_core/observability.py |
AgentTrace |
| Trace switch | app/config.py |
AGENT_TRACE_LOG_ENABLED |
| ReAct LLM/Tool events | app/llm/agent_metrics.py |
AgentMetricsCallback |
| ReAct run events | app/llm/agent.py |
stream_agent() |
| MultiStep step events | app/agent_core/agents.py |
MultiStepAgent.run_stream() |
| MultiStep trace injection | app/agent_core/runner.py |
stream_multistep_agent() |
| Safe request ID retrieval | app/utils/responses.py |
get_request_id() |
| Frontend META display | zzx-ai-agent-frontend/src/views/SuperAgent.vue |
runStats / [META] branch |
3.5 Switch and Viewing
AGENT_TRACE_LOG_ENABLED=1
AGENT_TELEMETRY_ENABLED=1
AGENT_TRACE_LOG_ENABLED: whether to outputagent.traceJSON logs;AGENT_TELEMETRY_ENABLED: whether to persist run/event to MySQL for the admin dashboard query.
Turn off:
AGENT_TRACE_LOG_ENABLED=0
Viewing:
- When running
python run.pylocally, view directly in the terminal; - In production, output to files or a collection system per logging config;
- Search for the
agent_traceprefix to extract JSON.
Example:
python run.py 2>&1 | grep "agent_trace"
4. Correspondence with smolagents
| smolagents | This project |
|---|---|
AgentMemory / MemoryStep |
AgentMemory / TaskStep / ActionStep |
write_memory_to_messages() |
AgentMemory.to_messages() + character budget |
truncate_content() |
utils.truncate_content() |
Timing |
Timing + duration_ms |
TokenUsage |
TokenUsage |
Monitor.update_metrics() |
AgentTrace.step_end() + [META] |
AgentLogger |
Project logging + agent.trace JSON |
replay() |
Not yet implemented; can be rebuilt from trace JSON |
| managed agents / rich console | Not introduced, keeping the project lightweight |
5. Tests
New tests:
ContextManagementTest.test_old_action_steps_are_omitted_and_messages_are_truncatedContextManagementTest.test_no_compaction_without_budgetObservabilityTest.test_structured_trace_events_are_json_and_content_free
Run:
cd zzx-ai-agent-backend
conda activate zzx-ai-agent
python -m unittest tests.test_agent_core -v
Full test suite:
python -m unittest discover -s tests
6. Langfuse Integration Evaluation
Langfuse integration (Cloud and self-hosted) was evaluated. The current conclusion is to keep the sink extension point but not integrate yet. The main reasons: the local admin observability dashboard already covers current needs; integration would add extra SDKs, data pipelines, and privacy boundaries; self-hosting would also require maintaining Postgres, ClickHouse, Redis, and object storage.
Detailed evaluation, cost comparison, and future trigger conditions are in: Agent Telemetry Dashboard Design.
7. Limitations and Next Steps
7.1 Current Limitations
- Character budget is not a token budget; different tokenizers will have deviations;
- Dropping old steps is a deterministic strategy; it does not use an LLM to semantically summarize old steps;
- ReAct's scratchpad has not yet received a run-level character budget;
agent.tracecurrently outputs to logs, is not persisted to a database, and has no OpenTelemetry/Jaeger integration;- Historical steps that are dropped cannot be replayed; only
omitted_stepscan be seen in the logs.
7.2 Possible Next Steps
- Integrate a model tokenizer for precise token budgeting;
- Use an LLM to do rolling summaries of old steps;
- Write traces to
chat_runsor a separate table for a run dashboard; - Add OpenTelemetry spans;
- Add a
replaycommand to replay a run from traces; - Add custom message-trimming logic for ReAct.
8. Blog Summary
An Agent's context management cannot just be "remember all history". This time, borrowing smolagents' step-based memory and truncation approach, we implemented three layers of control: session-level summaries, run-level recent-step budgets, and message-level Observation truncation. At the same time, observability expands from "a single META summary" to four classes of JSON events: run / step / LLM / tool. This both keeps token costs under control and makes it possible to locate the specific step when a problem occurs, without writing user content and tool arguments into logs.
Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.
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