跪拜 Guibai
← Back to the summary

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:

But two pieces are still missing:

  1. Context budget for a single Agent run: previously each step replayed all historical steps, so long tasks would grow without bound;
  2. 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:

Strategy:

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:

Core strategy:

  1. Always keep the system prompt and TaskStep;
  2. Only look at the most recent MULTISTEP_CONTEXT_KEEP_STEPS ActionSteps;
  3. Discard earlier ActionSteps as whole steps, without splitting the assistant tool_call and tool response;
  4. After discarding, insert a [上下文压缩] (context compression) hint to tell the model how many steps were omitted;
  5. Truncate a single message when it exceeds MULTISTEP_CONTEXT_MESSAGE_CHARS;
  6. 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":

2.4 Message Level: Observation and Code Output Truncation

Already present:

Newly added:

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:

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:

Logs do NOT record:

The admin Telemetry table additionally stores raw questions and final answers for the observability dashboard review; they do not go into agent.trace logs, 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

Turn off:

AGENT_TRACE_LOG_ENABLED=0

Viewing:

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:

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

  1. Character budget is not a token budget; different tokenizers will have deviations;
  2. Dropping old steps is a deterministic strategy; it does not use an LLM to semantically summarize old steps;
  3. ReAct's scratchpad has not yet received a run-level character budget;
  4. agent.trace currently outputs to logs, is not persisted to a database, and has no OpenTelemetry/Jaeger integration;
  5. Historical steps that are dropped cannot be replayed; only omitted_steps can be seen in the logs.

7.2 Possible Next Steps


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.

Comments

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.

CRZZX

Clever