Zero Labs
Industry News / AI

Context Engineering: What I Changed in My Agents (And Why Prompt Engineering Isn’t Enough)

Source · Towards AI By Elliott Girard

From the publisher’s feed, collected in the ZeroLabs newsroom.

Prompt engineering gets you a demo. Context engineering gets you a product. Here’s the architecture I use across every agent I build.The Shift Nobody Warned Me AboutFor the past year, I’ve been building AI agents professionally — for myself and for clients. Trading agents, email assistants, calendar bots, research tools. And the single biggest improvement in agent quality didn’t come from a better model, a smarter prompt, or a new framework.It came from rethinking what goes into the context window and when.Prompt engineering is about crafting the right instructions. Context engineering is about orchestrating the right information at the right time — instructions, memory, skills, user context or entreprise context, conversation history — so the model has exactly what it needs to make good decisions, and nothing more.The distinction matters because most agent failures I see in client work aren’t reasoning failures. The model is smart enough. They’re context failures: the model didn’t have the right information, or it had too much irrelevant information, when it needed to make a decision.This article is about the architecture I’ve converged on after building dozens of agents. Six layers that compose the context window dynamically, so every token serves a purpose.The Context Engineering StackHere’s the architecture I’ve converged on right now. It’s not a linear pipeline where every layer stacks on top. It’s two zones with different behaviors.Generated from mermaid diagram by the author with Claude Opus 4.6Zone 1: Pre-injected (always present, lightweight)Three layers that are always in the context window before the conversation starts:- Dynamic System Prompt — the agent’s identity, current time, state, behavioral constraints. Adapted to the moment, not written once at deployment.- Skill Server — three meta-tools at startup (list, load, unload). The agent loads rich tool descriptions only when it needs a specific capability.- User Memory — preferences, profile, tier. Simple, stable information that rarely changes within a session.Zone 2: Active/Passive (tunable depth)Three layers that exist at two levels of depth, and this is where the real engineering happens:- Agent Memory — what the agent learned from previous runs- Knowledge Graph — entities, relationships, and timeline from Graphiti, abotu the user.- Conversation Context— managed history of the current and past sessionsEach of these has a optionnal passive mode and a mandatory active mode.Passive means a lightweight summary is auto-injected into the context at the start of each interaction. The last 5 agent learnings. The top 3 relevant facts from the knowledge graph. A condensed summary of older messages. This costs maybe 500–800 tokens total and gives the agent enough background to handle most interactions, and must be done on a clean not to wide database in order to make realy time efficient retrival.Active means the agent has tools to go deeper when it needs to. It can search agent memory for specific patterns (“what worked last time I analyzed options?”). It can query the knowledge graph for entity timelines (“how has NVDA sentiment changed over the past week?”). It can look up specific past conversations (“what did the user say about their risk tolerance?”).Generated from mermaid diagram by the author with Claude Opus 4.6The critical point: you control the dial. For a simple query like “what’s the price of AAPL?”, the agent uses the pre-injected layers plus passive context — maybe 2,000 tokens total. For a complex multi-session analysis, it actively retrieves deeper context — up to 10,000–15,000 tokens. The architecture adapts to the task, and you configure the defaults and thresholds.Generated from mermaid diagram by the author with Claude Opus 4.6This is what makes it engineering, not just prompting. You’re designing a system where the context window composition is dynamic, controllable, and optimized for each interaction — not a static dump of everything the agent might need.Let me walk through each layer in detail.Layer 1: Dynamic System PromptMost developers write one system prompt and ship it. The agent gets the same instructions whether the user is asking for a stock analysis at 8am on a Monday or chatting casually on a Sunday evening.A dynamic system prompt adapts to the current context before the conversation even starts.Generated from mermaid diagram by the author with Claude Opus 4.6What I inject dynamically:- Current date and time— sounds trivial, but an agent that knows it’s Saturday won’t suggest “check the market opening” and an agent that knows it’s 2am won’t propose scheduling a meeting in 30 minutes- User specs and permissions — a free user on Wasaphi gets different guidelines than a premium user (model availability, credit budget) but it can be description about the job, the type of the user everything you have with the user id that will specialize the agent to the user- Agent state — which skills are currently loaded, any pending scheduled tasks, recent errors- Behavioral constraints— adjusted based on the domain. A financial agent gets strict disclaimer rules. A calendar agent gets time-parsing guidelines.def build_system_prompt(user, agent_state, current_time): sections = [ load_base_identity(), build_time_context(current_time), build_user_context(user), build_active_skills_summary(agent_state), build_behavioral_constraints(user.tier), ] return "\n\n".join(sections)The system prompt becomes a living document that reflects the current reality, not a static set of instructions written months ago.Layer 2: Skill Server (On-Demand Tool Loading)I wrote a dedicated article about this last week, so I’ll keep this concise. The core idea: don’t load all tools at startup. Load them on demand with rich descriptions.Generated from mermaid diagram by the author with Claude Opus 4.6Why this is context engineering, not just optimization:The point isn’t saving tokens — though you do. The point is that when a skill is loaded in isolation, you can afford to give each tool a comprehensive description: when to use it, when not to use it, how to interpret the results, what workflows to follow. That richness in the context directly translates to better tool selection and better outputs.With 40 tools competing for space, every description gets trimmed to the minimum. With 5 tools loaded on demand, each one gets the documentation it deserves.Layer 3: User MemoryThe agent should know who it’s talking to — not just their name, but their preferences, their history, and their patterns.Generated from mermaid diagram by the author with Claude Opus 4.6What I store for each user in Wasaphi:- Explicit preferences— risk tolerance, preferred analysis depth, language, notification preferences- Observed patterns — which tickers they ask about most, which features they use, what time they’re typically active- Interaction summaries — not the full conversation history, but distilled summaries of past sessions. “Last session: analyzed NVDA options flow, decided to wait for earnings”How it gets into context:def build_user_context(user) -> str: return f"""USER CONTEXT:- Name: {user.name}- Risk profile: {user.risk_tolerance}- Preferred depth: {user.analysis_depth}- Language: {user.language}- Frequently analyzed: {', '.join(user.top_tickers)}- Last session: {user.last_session_summary}- Note: {user.custom_instructions or 'None'}"""This is lightweight — maybe 200 tokens. But it transforms the interaction. The agent doesn’t ask “what’s your risk tolerance?” every time. It doesn’t suggest crypto to someone who only trades blue chips. It remembers.The key: user memory is explicit and transparent. The user can see what the agent knows about them and modify it. No hidden profiling.Layer 4: Agent Memory (What the Agent Learned)This is the layer most people miss entirely. User memory is about the user. Agent memory is about what the agent has learned from its own execution.Generated from mermaid diagram by the author with Claude Opus 4.6What goes into agent memory:- Tool reliability — “SEC filing tool has 15% timeout rate after 4pm EST. Prefer calling it during market hours.”- Output calibration— “User feedback indicates options analysis should be 3 paragraphs max, not 5.”- Workflow optimizations — “For multi-ticker analysis, always use the meta-tool. Individual calls hit iteration limits after 3 tickers.”- Error patterns — “Reddit API rate limits hit after 25 requests/minute. Space calls accordingly.”How I implement it:After each agent run, a lightweight post-processing step extracts learnings and stores them. Before the next run, relevant learnings are injected into the context as operational guidelines.# After each runasync def extract_learnings(run_result): """Extract operational learnings from agent run.""" learnings = [] if run_result.had_tool_errors: learnings.append(f"Tool '{run_result.failed_tool}' failed: {run_result.error_type}") if run_result.hit_iteration_limit: learnings.append(f"Task '{run_result.task_type}' exceeded iteration budget. Consider meta-tools.") if run_result.user_feedback == "too_verbose": learnings.append(f"Output for '{run_result.task_type}' should be shorter.") await memory_store.save_learnings(learnings)# Before each runasync def get_operational_guidelines(): """Retrieve relevant learnings for current context.""" recent = await memory_store.get_recent_learnings(limit=10) return "OPERATIONAL NOTES:\n" + "\n".join(f"- {l}" for l in recent)This is how agents get better over time — not by retraining the model, but by accumulating operational knowledge that shapes future context.Layer 5: Temporal Knowledge Graph (Graphiti)This is the deepest layer, and the one that changes the most about how agents understand the world.Traditional RAG stores chunks of text and retrieves them by similarity. It works for static knowledge bases. It fails for anything that changes over time.A temporal knowledge graph stores entities, relationships, and events — all timestamped. It understands that facts have a beginning and an end.Generated from mermaid diagram by the author with Claude Opus 4.6What I store in Graphiti:Generated from mermaid diagram by the author with Claude Opus 4.6Why temporal matters for agents:When my trading agent runs a morning analysis and finds “NVDA bullish sentiment 73%,” that fact is stored with a timestamp. When the same agent runs again the next morning, it can compare: “Yesterday NVDA was 73% bullish, today it’s 58%. Sentiment is declining.”Traditional RAG can’t do this. It would return both data points without understanding which is current or that a trend exists.How it fits into the context stack:Before each agent run, relevant knowledge is retrieved from Graphiti and injected into the context. The retrieval is scoped by time and relevance:async def get_graph_context(query: str, user_id: str) -> str: """Retrieve relevant temporal knowledge for the current query.""" # Search for relevant entities and relationships nodes = await graphiti.search_nodes(query, max_nodes=5) facts = await graphiti.search_memory_facts(query, max_facts=10) if not nodes and not facts: return "" # No relevant knowledge — don't waste tokens context = "KNOWLEDGE CONTEXT:\n" for fact in facts: context += f"- {fact.summary} (as of {fact.timestamp})\n" return contextThe knowledge graph is also where cross-agent learning happens. If I discuss a project in Claude Desktop and then switch to Cursor, the knowledge graph retains the context. One memory, every tool. (I wrote about setting this up with Graphiti in a previous article.)Layer 6: Conversation Context ManagementThe simplest layer conceptually, but the one that causes the most problems at scale: how do you manage conversation history as it grows?The strategy I use:- Keep the last 10–20 messages in full — this is the immediate conversational context the model needs for coherent responses- Summarize older messages — a periodic summarization step condenses messages 9+ into a running summary- Extract key decisions to agent memory — if the user made a decision (“let’s go with PostgreSQL”), that goes into the knowledge graph, not just the chat history- Sanitize large outputs — tool results that return 5,000+ tokens (HTML reports, raw API data) get replaced with summaries in the history. The full content served its purpose in the moment; it doesn’t need to persist always, store it in a file storage accessible to the agent and it can retrieve it if necessary with the rightdef manage_conversation_context(messages, max_recent=8): """Keep conversation context manageable.""" if len(messages) return messages # Short conversation, keep everything # Summarize older messages old_messages = messages[:-max_recent] summary = summarize_messages(old_messages) # Sanitize large tool outputs in recent messages recent = messages[-max_recent:] for msg in recent: if len(msg.content) > 2000: msg.content = truncate_with_summary(msg.content) return [{"role": "system", "content": f"Previous context: {summary}"}] + recentThis is also where the content sanitization from my trading agent article applies. Those beautiful HTML reports Wasaphi generates? They’re 10,000+ tokens of HTML. In the conversation history, they become “✅ Daily report generated and sent” — 8 tokens instead of 10,000.How the Layers Work TogetherHere’s the complete flow for a single agent interaction:The user sees a simple response. Behind the scenes, six layers assembled the right context, the agent loaded the right tools with rich descriptions, and the results were stored for future use.The Honest AssessmentThis architecture is not simple. Six layers is a lot of moving parts.But here’s what I’ve learned: you don’t build all six at once, and not every agent needs all six. My calendar bot uses layers 1, 3, and 6 — that’s it. Wasaphi uses all six because it’s a complex, multi-session product where context quality directly affects financial decisions.The framework is a menu, not a mandate. Pick the layers that address your actual failure modes.What matters is understanding that the context window is not just a place to dump a system prompt and hope for the best. It’s an engineered space where every token should earn its place.That’s context engineering. And once you start thinking about it this way, you won’t go back to static prompts.Thanks for reading! I’m Elliott, a Python & Agentic AI consultant and entrepreneur. I write weekly about the agents I build, the architecture decisions behind them, and the patterns that actually work in production.If this was useful, I’d appreciate a few clap 👏 and a follow. And if you’re implementing context engineering in your own agents, I’d love to hear how you did it — drop a comment.Context Engineering: What I Changed in My Agents (And Why Prompt Engineering Isn’t Enough) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.