User Agents

Web browsers and everyday web tech, explained

Reduce Context Bloat in Browser Automation Agents

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Context bloat happens when a browser automation agent accumulates too much history, page snapshots, or tool outputs in its working memory, causing slower responses, higher costs, and eventually failed tasks. This guide shows you how to keep the agent’s context lean and focused, so it runs faster and more reliably.

What You'll Need

  • Access to the browser automation framework or agent code you're using (e.g., Playwright, Puppeteer, Selenium, or a custom agent).
  • Basic familiarity with the agent's configuration files or prompt templates.
  • A way to log or inspect the agent's context (e.g., debug mode, console logs, or a monitoring dashboard).

Step-by-Step

  1. Identify what's consuming context. Enable logging that shows the token count or character count of each message, tool call, and page snapshot. Look for patterns: large DOM dumps, repeated screenshots, or long conversation histories.
  2. Limit page snapshot size. Instead of sending the entire HTML or DOM, extract only the relevant elements (e.g., via CSS selectors or XPath) and send a simplified text representation. For example, use page.textContent() or a custom scraper that strips scripts and styles.
  3. Summarize or truncate older interactions. If the agent keeps a conversation log, replace older turns with a short summary. For instance, after every 10 steps, generate a one-sentence recap of what was accomplished and discard the raw details.
  4. Use a sliding window for history. Keep only the last N steps (e.g., 5–10) in the active context. Older steps can be stored externally and fetched only if needed, but avoid loading them all back.
  5. Compress tool outputs. If a tool returns a large JSON or CSV, truncate it to the first few hundred characters and note that it's truncated. Or, have the tool return a summary instead of raw data.
  6. Set explicit context budgets. Define a maximum token count for the entire context. When the budget is exceeded, force a cleanup: drop the oldest messages, summarize, or end the current task and start a fresh session.
  7. Filter out irrelevant page elements. Before sending a page snapshot, remove navigation menus, footers, pop-ups, and hidden elements. Use heuristics like element.offsetParent === null to detect hidden nodes.
  8. Use separate memory for long-term facts. Store key data (like user credentials, URLs, or task goals) in a separate memory store (e.g., a file or database) and only inject it into context when needed, not on every step.
  9. Batch actions where possible. Instead of making 10 separate tool calls, combine them into one call that returns a combined result. This reduces the overhead of multiple round-trips.
  10. Monitor and iterate. After implementing the above, run your agent on a test task and observe the context size. Adjust thresholds and summarization strategies based on what you see.

Common Mistakes

  • Truncating too aggressively. Cutting off important information can cause the agent to lose track of the task. Always keep the goal and recent steps intact.
  • Ignoring hidden state. Some agents keep state in variables or browser storage that also counts toward context. Clear or reset these when they're no longer needed.
  • Over-summarizing. Summaries that are too vague or lose critical details (like exact URLs or error messages) will lead to mistakes. Make sure summaries retain action-specific facts.
  • Not testing after changes. Reducing context can change behavior. Always run a regression test on a few typical tasks.
  • Using screenshots as primary context. Screenshots are heavy. Use them sparingly, and prefer text-based snapshots for most steps.

Tips

  • Use a structured format for summaries, like Action: clicked button; Result: form submitted.
  • If your agent supports it, use a “memory” system that automatically archives old turns and retrieves them only when a keyword matches.
  • Consider using a smaller, faster model for summarization steps to avoid double cost.
  • Set a hard limit on the number of steps per task (e.g., 50) and force a restart if exceeded.
  • Log the context size at each step to a file so you can analyze trends over time.
  • For DOM extraction, use a library like readability to get the main content only.

Troubleshooting

  • Agent still runs out of context. Check if there are large system messages or instructions that are repeated. Move static instructions to a separate prompt that isn't re-sent every time.
  • Agent forgets important details. Your summarization is too aggressive. Keep the last few raw steps and only summarize older ones. Also, ensure the summary includes exact values like numbers and names.
  • Performance didn't improve. The bottleneck might be network latency or the model itself, not context size. Profile the agent to confirm where time is spent.
  • Summaries are inaccurate. Use a dedicated summarization prompt that asks for specific fields (goal, last action, next action, errors). Test the summary on a sample conversation.
  • Agent behaves differently after changes. Roll back changes one by one to identify which one caused the regression. Use A/B testing on a small set of tasks.

Frequently Asked Questions

How do I measure context size?

Most frameworks expose token counts in logs. If not, estimate by counting characters in the serialized context and dividing by 4 (roughly 4 chars per token for English).

Can I use a vector database to store past interactions?

Yes, but it's overkill for most tasks. A simple JSON file or a list of summaries works fine for short sessions. Vector retrieval adds complexity and latency.

Should I clear context after every task?

Yes, if tasks are independent. If tasks are related, keep a short summary of the previous task's outcome.

Is it better to use a smaller model to reduce cost?

Smaller models have smaller context windows, so they force you to be lean. But they may also be less capable. Start with a larger model and optimize context first, then consider model size.

How do I handle pages with dynamic content?

Take a snapshot only after the page has settled (e.g., wait for network idle). Then extract only the changed parts, not the whole DOM.

What if my agent needs to remember a long sequence of steps?

Break the task into sub-tasks, each with its own context. After each sub-task, store a summary and start fresh for the next one.