Zero Labs
Industry News / AI

Modular System Prompts: How I Build Agents That Adapt to Every Session

Source · Towards AI By Elliott Girard

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

The dynamic system prompt isn’t a layer. It’s a compiler. And Anthropic’s own leaked code proves it.The ConfessionIn Context Engineering: What I Changed in My Agents, I introduced the dynamic system prompt as Layer 1 of a six-layer context stack. I gave you a five-line build_system_prompt() function and moved on.That function was a lie of omission.In production, that single function is the most engineered piece of code in my agents. It’s not “a layer.” It’s a compiler that turns the current state of the world — who’s talking, what time it is, which skills are loaded, what tier the user is on, what just failed — into the exact instructions the model needs for the next turn.I could have kept telling you “trust me, this matters.” But I don’t have to anymore. Because in March 2026, Anthropic accidentally shipped a 59.8 MB source map in the Claude Code npm package, exposing 512,000 lines of TypeScript. The community read it. The architecture got dissected.And what they found was exactly this pattern.What the Claude Code Leak Actually ShowedThe most interesting discovery wasn’t the unreleased features or the internal codenames. It was a constant in the source: SYSTEM_PROMPT_DYNAMIC_BOUNDARY.Claude Code’s system prompt is split in two. Everything before that boundary — base identity, tool definitions, behavioral rules — is cached globally across every organization on every request. Everything after — your CLAUDE.md, your git status, the current date, the active model context — is session-specific and assembled per call.Two things to take from that:Even the best team in the industry doesn’t write one static system prompt. They compose it. The Claude Code prompt is modular by construction, with a cache-aware boundary engineered into the architecture.Prompt engineering isn’t a “first draft” task you finish on day one. Internal comments in the leak reference A/B tests on concision — “research shows ~1.2% output token reduction vs qualitative ‘be concise’” — and explicit word-count caps for inter-tool text. The team at Anthropic treats their system prompt like production code, because it is production code.Static system prompts are why your agent is dumber than it should be. Modular system prompts are why mine isn’t. And now we know they’re why Anthropic’s isn’t either.This article is the deep dive I should have written months ago.Why Static Prompts Fail (Even Good Ones)Most agents I audit have one of two problems with their system prompt:Problem 1: The Monolith. A 4,000-token system prompt that tries to cover every scenario. Risk disclaimers for finance, time-handling for scheduling, output format rules for reports, error recovery for tool failures. All of it. Every turn.The result: the model is drowning in instructions that don’t apply to the current request. When the user asks “what’s the time in Tokyo?”, they’re paying 4,000 tokens of irrelevant context. Worse — the model’s attention is split across rules that contradict each other when read out of context.The cost of cramming every rule, every tier, every edge case into a single static prompt: the model can’t find the signal under the noise.Problem 2: The Minimalist. A 200-token system prompt that says “You are a helpful assistant. Use the tools available.” Then the developer is shocked when the model hallucinates, forgets constraints, treats Saturday like Wednesday, narrates every intermediate step, or asks permission for things it should just do.Both fail for the same reason: the system prompt is treated as configuration, not as code.Without a proper modular prompt, your agent isn’t proactive. It’s verbose. It has no personality. It has no situational awareness. It can’t adapt to the user it’s talking to. It’s a generic assistant pretending to be your product.A modular system prompt isn’t a string. It’s the output of a function that runs every turn.The Architecture: System Prompt as CompositionHere’s the model I use across every production agent:build_system_prompt(session_context) -> str │ ├─ Section: Agent identity [always] ├─ Section: Communication & efficiency [always] ├─ Section: Proactive behavior [always] ├─ Section: Temporal context [always] ├─ Section: User profile [if authenticated] ├─ Section: Tier constraints [if tiered] ├─ Section: Shell & diagnostics [if shell tool available] ├─ Section: Workspace context [if in shared workspace] ├─ Section: Active skills summary [if skills loaded] ├─ Section: Behavioral guards [conditional] ├─ Section: Recovery context [if previous error] └─ Section: Session intent [if inferred]Each section is a pure object: it has a name, a content string, an ordering rank, and a prerequisite_met flag. The system prompt is the concatenation of every section whose prerequisite was met, sorted by canonical order.python@dataclassclass PromptSection: name: str content: str order: int prerequisite_met: bool = Truedef build(self) -> str: active = sorted( [s for s in self._sections if s.prerequisite_met], key=lambda s: s.order, ) return "\n\n".join(s.content for s in active)That’s the whole pattern. The complexity moves into the sections, where it belongs.A few rules I enforce in the builder itself:Order is canonical, not negotiable. Identity comes first. Recovery context comes after profile. Skills summary comes after constraints. I keep the ordering in the section definition, not in the assembly logic.Sections are introspectable. I can ask the builder which sections are active right now, and I can parse an assembled prompt back into its sections for debugging.The token budget is real. I track an approximate token count of framework-added sections, excluding the agent’s domain identity and the skills discovery prompt. If a section would push the assembly over budget, the lowest-priority one drops.That introspection is what saves you at 2am when the agent does something weird and you need to know exactly what it saw.Section 1: Agent Identity (Always)The non-negotiable core. Who the agent is, what it can and cannot do, how it speaks.pythondef block_identity() -> str: return """You are Wasaphi, an AI trading assistant. Core principles: - You analyze markets. You never recommend specific trades. - Every analysis includes confidence and limitations. - You speak directly. No hedging that obscures meaning."""This is the only section that’s nearly static. Even here, I version it — when I change the agent’s tone or core constraints, I bump a version so I can A/B test against past runs.Section 2: Communication & Efficiency (Always)This is the section that gives the agent its voice and discipline. Without it, your agent narrates every step, repeats the user’s question back at them, and dumps raw tool errors into chat.## Communication & Efficiency- Provide concise responses focused on results, not process descriptions.- Use structured formatting (bullet points, code blocks, tables) for technical information.- State what was done and what the result is. Do not narrate each intermediate step.- Do not repeat information already visible in the conversation context.- When encountering an error, report it with a diagnosis and proposed next steps — never forward raw error output without interpretation.Notice the parallel to the Claude Code A/B test: explicit, measurable rules beat vague ones. “Be concise” is wishful thinking. “Do not narrate each intermediate step” is enforceable behavior.Section 3: Proactive Behavior (Always)The single most underrated section. Most agents I audit ask permission before doing anything. This section flips the default.## Proactive Behavior- Attempt actions before asking clarifying questions. Use available tools to gather information rather than asking the user for details you can discover yourself.- Complete multi-step tasks in a single response when all required information is available or discoverable via tools.- When a request is ambiguous, attempt the most likely interpretation and state the assumption made. Only ask for clarification when multiple interpretations would lead to fundamentally different outcomes.- Report results concisely without repeating the original request.The difference between an agent that feels capable and one that feels like a chatbot is almost entirely here. A capable agent reads the environment, makes an assumption, states it, and acts. A chatbot stops every 10 seconds to verify it’s still allowed to breathe.Section 4: Temporal Context (Always)The single highest-ROI section in the entire architecture. It costs 40 tokens and prevents an entire class of failures.pythondef block_temporal(now: datetime) -> str: user_tz = now.astimezone() is_weekend = user_tz.weekday() >= 5 market_status = get_market_status(user_tz) return f"""CURRENT TIME CONTEXT:- Now: {user_tz.strftime('%A, %B %d, %Y at %H:%M %Z')}- Weekend: {is_weekend}- US market: {market_status}- Day boundary: any reference to "today" means {user_tz.date()}"""Without this, an agent will confidently tell you the market is open on a Sunday. With this, it knows.Notice what’s not here: I don’t dump a calendar. I don’t list holidays for the next year. I inject only what’s true right now. Tomorrow’s prompt will have tomorrow’s context. The prompt is regenerated every turn.This is the same logic as Claude Code’s dynamic boundary — current date sits after the cache boundary, exactly because it has to change per call.Section 5: User Profile (Conditional)Only injected if the user is authenticated. Even then, only the dimensions that affect behavior.pythondef block_user_profile(user: User | None) -> str: if not user: return "" return f"""USER PROFILE:- Name: {user.display_name}- Language: {user.language}- Risk profile: {user.risk_tolerance}- Preferred response depth: {user.depth_preference}- Frequently analyzed: {', '.join(user.top_tickers[:5])}"""The discipline here: resist the urge to add more. Every field you add costs tokens on every turn for every user. If a field doesn’t change agent behavior, it doesn’t belong in the system prompt. It belongs in active memory the agent can query when relevant.Section 6: Tier Constraints (Conditional)This is where most monolithic prompts go wrong. They list every tier’s rules in one section and let the model figure out which apply.The modular approach: inject only the rules for the current user’s tier.pythonTIER_CONSTRAINTS = { "free": """TIER CONSTRAINTS (free):- Maximum 3 deep analyses per day- No portfolio tracking- Suggest premium upgrade only if user asks about advanced features""", "premium": """TIER CONSTRAINTS (premium):- Unlimited deep analyses- Portfolio tracking enabled- Custom alerts available""",}The free-tier user never sees the premium rules. The premium user never sees the free-tier limits. The model isn’t confused by “what does this user have access to?” — the context already answered that question.Section 7: Shell & Diagnostics (Conditional)Only injected if the agent has a shell execution tool — which it should, if you read 9 Tools. That’s All Your Agent Actually Needs.## Shell Usage & DiagnosticsDiagnostics first: Before reporting a problem to the user, use shell_execto verify connectivity, test commands, and diagnose the issue yourself.Environment discovery: Read environment variables via shell_exec(`echo $VAR_NAME` or `env | grep PATTERN`) to discover available serviceendpoints and credentials. Do not ask the user for values that areavailable in the environment.Dependency auto-install: When shell output shows an ImportError, detectthe missing package, install it with `uv pip install`, and retry thefailed command. Install only the specific missing package.Without this section, the agent has the tool but doesn’t know how to think with it. With it, the tool becomes a habit.Section 8: Workspace Context (Conditional)For agents operating in shared environments — multi-user workspaces, team contexts, organization-level deployments.## Workspace ContextSecrets as env vars: Workspace entities marked as secrets are availableas environment variables in shell_exec. Access them via $VARIABLE_NAME.NEVER expose secret values in your text responses.Service discovery: Infer available services from entity names(e.g., ELASTICSEARCH_URL implies Elasticsearch access). Test serviceconnectivity via shell_exec before reporting access issues.This section doesn’t exist for solo-user agents. The whole point of prerequisite_met is that you don't pay tokens for context that doesn't apply.Section 9: Active Skills Summary (Conditional)If you’re using the 9-tool framework, this is where loaded skills announce themselves.pythondef block_active_skills(skills: list[Skill]) -> str: if not skills: return "" lines = ["ACTIVE SKILLS:"] for skill in skills: lines.append(f"- {skill.name}: {skill.one_line_purpose}") lines.append("\nUse list_skills if you need a capability not in the active set.") return "\n".join(lines)The detail of how to use each skill lives in the skill’s own SKILL.md, loaded into context when the skill is loaded. The system prompt just maintains awareness of what's available right now.Section 10: Behavioral Guards (Conditional)This is the section that protects against domain-specific failures. It’s conditional on signals from the current session.pythondef block_behavioral_guards(ctx: SessionContext) -> str: guards = [] if ctx.current_time.hour 22: guards.append( "- It is outside normal hours. Do not propose scheduling " "actions for the next 30 minutes without confirmation." ) if ctx.agent_state.iteration_count > 7: guards.append( "- You have used many tool calls this turn. " "Move toward a final answer rather than further exploration." ) if ctx.agent_state.recent_tool_errors >= 2: guards.append( "- Multiple tool errors recently. Verify tool inputs carefully " "and consider asking the user to confirm before retrying." ) if not guards: return "" return "BEHAVIORAL GUARDS:\n" + "\n".join(guards)These guards are invisible to the model when the conditions don’t apply. They only appear when they’re relevant. The model isn’t trained to ignore the budget warning when there’s no budget pressure — it never sees the warning in the first place.Section 11: Recovery Context (Conditional)When the previous turn failed, the next system prompt acknowledges it.pythondef block_recovery_context(last_error: AgentError | None) -> str: if not last_error: return "" return f"""RECOVERY CONTEXT:The previous attempt failed: {last_error.summary}.- Failed tool: {last_error.tool_name}- Reason: {last_error.reason}- Do not retry the same approach. Either try a different tool or ask the user for clarification."""Without this, the model retries the same broken call three times in a loop. With it, the failure is upgraded from “raw error in context” to “actionable instruction at the top of attention.”Section 12: Session Intent (Conditional)The most experimental section. If the routing layer or a classifier inferred the session’s intent, inject it.pythondef block_session_intent(intent: Intent | None) -> str: if not intent or intent.confidence return "" return f"""LIKELY SESSION INTENT (inferred, confidence {intent.confidence:.0%}):- Goal: {intent.goal}- Suggested first action: {intent.suggested_action}- If this doesn't match the user's actual request, ignore it."""That last line matters. Inferred intent is a hint, not a command. The deterministic shell suggests; the probabilistic core decides. (See Deterministic Shells, Probabilistic Cores for the full pattern.)What Gets Composed in PracticeThree scenarios from the same agent, same day:Scenario A — Free user, casual query at noon:[Identity] + [Comms] + [Proactive] + [Temporal] + [Profile] + [Tier: free] + [Skills]≈ 800 tokensScenario B — Premium user, deep analysis at 3am after a tool error:[Identity] + [Comms] + [Proactive] + [Temporal] + [Profile] + [Tier: premium] + [Skills] + [Guards: late hour + recent errors] + [Recovery]≈ 1,500 tokensScenario C — Anonymous landing-page query:[Identity] + [Comms] + [Proactive] + [Temporal] + [Tier: anonymous]≈ 400 tokensSame agent. Same codebase. Three radically different system prompts, each optimized for its moment.Compare this to the monolithic alternative: 4,000 tokens of catch-all instructions on every turn. The modular approach pays for itself within a handful of interactions.The Discipline This DemandsModular prompts are not free. They require discipline I see most teams skip:1. Every section needs an owner and a test. When you add a guard, you write a test that triggers the condition and verifies the guard appears. When you remove a section, you check that the failure mode it prevented hasn’t returned.2. Section ordering matters. Identity always comes first. Recovery context comes after profile (so the model knows who failed before what failed). Order is part of the section definition, not part of the assembly logic.3. The token budget is real. I cap the assembled system prompt at ~2,000 tokens for most agents. The builder tracks this, not your good intentions.4. Snapshot every prompt for debugging. When something goes wrong, the first thing I need is the exact system prompt the model saw. I log every assembled prompt with a hash so I can diff across turns and across users. The builder exposes get_active_sections() and a parser that reconstructs sections from any assembled prompt — those exist specifically for this.5. Cache-aware boundaries if you’re at scale. This is the Claude Code lesson. Order your sections so the stable ones come first and the volatile ones come last. Your LLM provider’s prompt caching will reward you. At Wasaphi scale, this matters in your bill.When Modular Is OverkillI’ll be honest: not every agent needs this.If your agent has a single, narrow purpose — one tier, one user, one type of task, no time sensitivity — a static prompt may be fine. The complexity of modular composition isn’t worth it.The crossover point is roughly: two or more tiers, two or more session modes, or any agent that has to survive across time (where “now” matters). Below that, static works. Above it, static silently degrades your agent.If you’re not sure where you are, here’s the test: read your system prompt and count the instructions that don’t apply to the most common request your agent handles. If it’s more than three, you’ve crossed the line.The Pattern Beneath the PatternModular system prompts are an instance of the deeper pattern I’ve been writing about for months: deterministic shells around probabilistic cores.The model is brilliant and unpredictable. The shell’s job is to give it a consistent, controlled briefing for every interaction — assembled deterministically from the current state of the world.Anthropic figured this out. The leak proved it. The most engineered chunk of code in Claude Code isn’t the agent loop or the tool dispatcher — it’s the thing that decides what the model reads before it thinks.Your prompt is not a config file. It is the most important piece of code in your agent.Write it like code.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, drop a few claps 👏 and a follow. And if you’re building modular prompts in your own agents, I’d love to hear how — drop a comment.Modular System Prompts: How I Build Agents That Adapt to Every Session was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.