Alternar tema

Context engineering para agentes de IA: como separar System Prompt, Memory, Tools e Files

Easton editorial illustration: one central memory library linking recent notes to durable knowledge shelves

"Effective context engineering for AI agents"

Esta versão mantém a estrutura, as tabelas, as listas e os blocos de código da fonte chinesa, com adaptação ao contexto técnico brasileiro.

A team puts forty repository rules into the system prompt, and the agent still edits temporary logs as if they were source files. The rules say “only modify files under src”, “do not touch logs”, and “ask before deletion”, but by the fifth turn those constraints behave as if they were never present.

The problem is not that the model suddenly became careless. The problem is that every rule sits in the same layer. Rules, documents, state, memory, tool output, and user requests all compete for the same context budget.

This guide gives you a layered decision framework for eight context carriers: System Prompt, Memory, Files, Tools, State, Trace, Output Contract, and User Task. It also gives you a migration decision tree and an engineering audit checklist so you can move from rule piling to context governance.

Capítulo 1: From symptoms to root cause: why prompt rules still get forgotten

1.1 A real team case: forty rules in the system prompt, and file boundaries still fail

A code review agent has forty rules in its system prompt: only modify src, do not touch logs or tmp, ask before deleting, return JSON, use English comments, and write a commit message after each change.

The first three turns look fine. On turn four, the user asks it to clean up log files, and the agent runs rm -rf logs/. On turn five, the user asks whether temporary test files can be removed, and the agent deletes twelve files under tmp, including three fixtures still used by tests.

In the review, the team finds that “only modify src” was line 17, “do not touch logs” was line 23, and “ask before deletion” was line 31. Those rules worked early, but after tool output, retrieved documents, and intermediate reasoning filled the conversation, the original constraints became diluted.

This is why context has to be planned. Anthropic describes context as a limited resource that must be curated and managed, not a place to dump every rule.

1.2 Other common symptoms: mistaken tool calls, memory pollution, lost state, and context bloat

Mistaken tool calls: a tool description says only update_record: update a record. It does not say when not to call the tool, so the agent updates data when the user only asked to read it.

Memory pollution: on turn two, the agent remembers that the user prefers short answers. On turn eight, the user asks for a detailed explanation, but the old memory still forces short output. Cross-turn facts conflict because there is no update policy.

Lost state: the agent stops at step three, where it is generating test cases. After restart, it begins again at step one. Task progress lived only in the current context and was never persisted as runtime state.

Context bloat: every turn keeps prior tool results, retrieved snippets, and intermediate reasoning in the active context. By turn ten the token count is four times higher than turn one, but answer quality falls because noise crowds out the goal.

These symptoms share one root cause: context carriers do not have clear responsibilities.

1.3 Root cause: context carriers are unclear, so every rule crowds into one layer

In the OpenAI Agents SDK, instructions are not the only context carrier. An agent also sees user tasks, conversation history, retrieved documents, tool definitions, runtime state, and output contracts.

If forty rules all sit in the system prompt, they compete with user requests, documents, and tool outputs. When the context budget is finite, the model has to decide which constraint matters most among many competing inputs.

Redis frames the same issue as competition among system instructions, goal specification, conversation memory, tool results, retrieved documents, and intermediate reasoning. Each input competes for attention.

The failure is not simply that the model “forgets”. The rule is in the wrong place. Some rules belong in the System Prompt, some in Tool Description, some in Memory, and some in Files or Retrieval.

Capítulo 2: A layered context framework: eight carriers and six competing inputs

2.1 Overview of the eight context carriers

Agent context is not one container. It is a set of carriers with different jobs:

CarrierResponsibilityBest fit
System/Developer InstructionsRole, behavior boundary, output contractGlobal constraints, role definition, safety boundary
User TaskCurrent task goal and user inputDynamic task, query, request
MemoryUser preferences and cross-session factsShort-term memory inside a session, long-term memory across sessions
Retrieval/FilesSearchable documents and knowledge basesAPI docs, product manuals, code repositories
Tool Schema/DescriptionTool capability and invocation constraintsWhen to call, when not to call, risk boundaries
Runtime StateTask progress and branch choiceStep tracking, pending approvals
TraceCall history and audit logPost-run analysis, evaluation, review
Output ContractOutput format and validation rulesStructured output, downstream dependencies

OpenAI Agents SDK treats instructions as behavior guidance, not as the only source of context. LangGraph separates short-term thread state from long-term memory. Anthropic’s context engineering guidance points in the same direction: choose, compress, isolate, and update context instead of piling it up.

2.2 RAM vs Disk analogy

A useful analogy is RAM versus disk. The context window is like RAM: fast, expensive, and volatile. External storage is like disk: slower, cheaper, and durable.

RAM is a bad place for a changing knowledge base. If an API field changes from user_id to userId, a stale prompt snippet can make the agent call the wrong field. That information belongs in file search or retrieval, where the latest document can be retrieved when needed.

RAM is also not where cross-session user preferences should live. If the user once said they prefer concise answers, that preference should load from long-term memory in future sessions instead of being retyped into every prompt.

RAM is for constraints that must apply immediately: role, safety boundary, and output contract. These need high bandwidth and predictable visibility.

2.3 Six inputs competing for the context window

Six common inputs compete for the same context budget:

  1. System instructions — behavior guidance, role definition, and safety boundaries
  2. Goal specification — the current task goal and user query
  3. Conversation memory — conversation history inside the session
  4. Tool results — responses from tools and external APIs
  5. Retrieved documents — snippets retrieved from a vector store or knowledge base
  6. Intermediate reasoning — intermediate steps produced during the run

If system instructions take 2,000 tokens, the user goal takes 500, conversation memory reaches 3,000, tool results reach 5,000, retrieved documents take 2,000, and intermediate reasoning takes 1,000, the context already carries 13,500 tokens.

Finding “do not delete files” inside that pile is like finding one sentence in a long report. When the rule disappears by turn five, it may be because other inputs took over the available attention.

Capítulo 3: System/Developer Instructions: role definition and behavior boundaries

3.1 Instructions responsibility boundary

System Prompt, or the instructions field in the OpenAI Agents SDK, is best for:

  • Role definition: you are a code review assistant, or you are a data analysis agent
  • Behavior boundary: do not delete production files, do not call unauthorized APIs
  • Constraint rules: ask before every modification, include source links in every answer
  • Output contract: return JSON, include a status field

It is not a good place for:

  • User preferences: the user prefers short answers — put this in Memory
  • Searchable documents: API documentation — put this in Files/Retrieval
  • Tool invocation detail: when to call update_record — put this in Tool Description
  • Runtime state: step three is done — put this in Runtime State

The official SDK model makes this visible: instructions live beside tools, conversation history, retrieved documents, and other carriers. When every rule goes into instructions, the other carriers lose their job.

3.2 When Instructions are the right carrier

System Prompt is a strong fit for three categories:

  1. Global constraints: safety boundaries such as not deleting production data, behavior red lines such as not calling external APIs, consistency rules such as using English output
  2. Role definition: the agent’s identity and capability boundary, for example a code review assistant that reviews code but does not modify the runtime environment
  3. Output contract: output shape such as {status, data, error}, and validation requirements such as always including status

It is a poor fit for these categories:

  • Dynamic task goal: the user’s current request belongs in User Task
  • User preference: a prior preference for short answers belongs in Long-term Memory
  • Business knowledge base: API docs and manuals belong in Files/Retrieval

3.3 Common Instructions mistake: piling up rules

Mistake one: more rules make dilution easier. Forty rules in a system prompt leave the model guessing which one has priority once later tool output and documents enter the context.

Mistake two: conflicting rules do not resolve themselves. If the prompt says both “answer in detail” and “keep it short”, the model has no durable priority rule for when each applies.

Mistake three: rules fade across turns. A file boundary can work in turns one through three and fail in turn five. Long-running agents need memory, compaction, and tool-result clearing strategies, not only a longer prompt.

Capítulo 4: Memory: the boundary between short-term and long-term memory

4.1 Memory responsibility boundary: short-term vs long-term

TypeResponsibilityCarrierVolatility
Short-term memoryCurrent session historymessages list, checkpointsCleared when the session ends
Long-term memoryUser preferences and cross-session factsmemory store, vector storePersisted across sessions

LangGraph persistence treats short-term memory as thread state, stored through a checkpointer. Long-term memory goes into a store and needs explicit write, read, update, and expiry behavior.

4.2 When to write long-term memory

Good long-term memory candidates:

  • User preferences: the user is vegetarian, prefers short answers, or usually communicates in Chinese
  • Cross-session facts: the user mentioned a migration to AWS, or the project uses TypeScript
  • Procedural memory: this user likes to see code before explanation, or prefers concise responses

Poor long-term memory candidates:

  • Current task goal: the user’s present request belongs in User Task
  • Temporary session state: current task progress belongs in Runtime State

Mem0 describes memory types such as semantic facts, episodic events, and procedural preferences. Regardless of taxonomy, each memory needs a write path, an update path, and an expiry policy.

4.3 Memory vs Files/Retrieval

Question: what is the difference between memory and files/retrieval?

Answer: memory stores user preferences, cross-session facts, and task experience. Files and retrieval search external documents and knowledge bases.

Both need governance. Memory without update and expiry rules becomes polluted; a three-year-old preference may still apply. Retrieval without strategy adds noise; irrelevant documents consume tokens without improving the decision.

4.4 Memory mistakes: pollution and missing expiry

Mistake one: memory pollution. The agent stores “prefers short answers” on turn two. On turn eight the user asks for detail, but the old memory still wins.

Mistake two: missing expiry. A stale preference remains active long after the user changed their mind.

Mistake three: missing write strategy. Writing every conversation bloats memory; never writing anything loses real preferences.

LangGraph’s memory documentation makes the same point: memory needs explicit write, read, and update paths.

This section only defines memory’s boundary inside context layering. For memory types, storage choices, and governance policies, see Agent memory system design: from session to long-term memory.

Capítulo 5: Retrieval/Files: knowledge-base retrieval and file boundaries

5.1 Files/Retrieval responsibility boundary

Files/Retrieval is best for:

  • Searchable documents: API docs, product manuals, technical specifications
  • Knowledge bases that change by version: SDK docs, framework release notes
  • Large material: code repositories, historical datasets

It is not for:

  • Rules that must always be followed: do not delete files — put these in the system prompt or tool schema
  • User preferences: the user prefers short answers — put this in memory
  • Current task goal: the current user request belongs in user task

OpenAI’s file search documentation positions file search as knowledge retrieval. Retrieval provides information; it does not enforce behavior.

File search fits these cases:

  1. API documentation lookup: what fields the OpenAI Agents SDK tools object supports, or which backend LangGraph persistence recommends
  2. Product manual retrieval: feature usage notes and configuration ranges
  3. Repository search: implementation details for a function or dependencies of a module

It does not fit this case:

  • Global behavior rules: do not delete files, do not call unauthorized APIs — keep these in the system prompt

A file system or retrieval layer can mount context, but retrieved material is still reference material. If it must constrain behavior, pair it with instructions or tool schema.

5.3 File mistake: treating the knowledge base as a rule base

Mistake one: retrieved knowledge does not guarantee compliance. If “do not delete files” lives only in a knowledge base, the agent may retrieve it and still delete files.

Mistake two: knowledge bases are not for mandatory constraints. They are for reference material, not for safety boundaries or behavior red lines.

A practical threshold: short, stable material under 500 tokens that must be followed in the current run can go into the prompt.

Use these checks:

  • Short material under 500 tokens: a three-line YAML example or a five-field API schema → paste into the prompt
  • Long document over 500 tokens: a fifty-page API doc or a full code repository → use file search
  • Versioned content: SDK docs or framework release notes → use file search so the latest version can be retrieved
  • Must-follow current constraint: the current task’s boundary or urgent safety rule → paste into the prompt

Capítulo 6: Tool Schema/Description: a miniature behavior controller

6.1 Tool Description responsibility boundary: miniature behavior controller

Anthropic’s tool-writing guidance is useful here: a tool description is not just an API comment. It is a small behavior controller.

It should include:

  • Function: what update_record does
  • Input constraints: required and optional parameters
  • When to call: the situation in which the tool should be used
  • When not to call: read-only questions, missing authorization, or unsafe contexts
  • Risk boundary: what damage the call could cause
  • Return structure: output fields and their meaning

It should not be only:

  • A bare API comment: update_record: update a record
  • Missing invocation timing: no guidance on when not to call
  • Missing risk warning: no requirement for user confirmation

6.2 Tool Description structure elements

A practical tool description has six elements:

  1. Function: update_record updates a database record
  2. Input constraints: id and data are required; overwrite is optional
  3. When to call: call it when the user explicitly asks to update data
  4. When not to call: do not call it for read-only queries or without authorization
  5. Risk boundary: call only after user confirmation; never modify production data without authorization
  6. Return structure: return {status: "success", updated_id: string}

For example, the description should say that the tool may be called only after explicit confirmation and must not modify production data without authorization.

6.3 Tool Description mistakes: too short or too long

Mistake one: too short. update_record: update a record does not say when not to call, so the agent may update data during a read-only task.

Mistake two: too long. A 500-token description wastes the context budget. The six elements should usually fit in 100 to 200 tokens.

Mistake three: missing risk boundary. If confirmation is not mentioned, the agent may modify production data directly.

The agent did not miscall the tool because it was unintelligent. It miscalled the tool because the description did not define restraint.

6.4 Tool Description FAQ

Question: how detailed should a tool description be?

Answer: it should state the function, input constraints, when to call, when not to call, risk boundary, and return structure. Treat it as a small behavior controller, not as a backend API comment.

This section only defines tool description boundaries inside context layering. For the full tool-calling flow, evaluation, and tool governance, see Agent tool calling in practice.

Capítulo 7: Runtime State: task progress and branches

7.1 Runtime State responsibility boundary: progress and branches

Runtime State is best for:

  • Current task progress: step three is done, step four is running
  • Branch choice: the user chose option A and rejected option B
  • Pending approval: waiting for deletion confirmation, or waiting for the user to pick a branch

It is not for:

  • User preferences: the user prefers short answers — put this in memory
  • Global rules: do not delete files — put this in the system prompt

LangGraph persistence treats state as part of the thread. A paused task should resume from the right point instead of restarting from step one.

7.2 Runtime State vs Memory

Question: what is the difference between runtime state and memory?

Answer: runtime state is current task progress, branch choice, and pending approvals. Memory is information reused across tasks.

State should be recoverable after interruption. Memory should be governed through write, update, and expiry policies.

A simple distinction: state says “step three is done and deletion is waiting for approval”; memory says “this user prefers concise answers and mentioned an AWS migration earlier”.

7.3 Runtime State mistakes: lost state cannot recover

Mistake one: lost state. The agent stops while generating test cases and restarts from requirements analysis because no checkpoint stored the progress.

Mistake two: state pollution. Option A and option B states mix inside one context, and the agent cannot tell which branch is active.

Use a checkpointer or equivalent persistence layer so state survives interruptions and branch decisions stay isolated.

Capítulo 8: Trace: call history and audit

8.1 Trace responsibility boundary: call history and audit

Trace is best for:

  • Call history: update_record was called and returned success
  • Audit log: who approved deletion and when a configuration changed
  • Post-run analysis: why the agent chose the wrong path or which tool was misused

It is not for:

  • Current decision input: that belongs in conversation memory or current tool output
  • User preference: that belongs in memory

Trace-based evaluation is for analysis and review. It is not the same thing as active context for the current turn.

8.2 Trace vs Conversation Memory

Question: what is the difference between trace and conversation memory?

Answer: trace is call history and audit information for later analysis. Conversation memory is decision input inside the current session.

Trace can be persisted, but it does not need to be loaded into the model for every decision.

8.3 Trace mistake: using trace as decision input

Mistake one: trace gets too long. All historical calls stay in context, so by turn ten the model sees nine turns of tool history that it does not need.

Mistake two: trace is misused. Audit logs become decision inputs, and the agent relies on old tool results instead of the current user task and current tool output.

Tool clearing helps here. Move old tool results into trace and keep only the current results in the active context.

Capítulo 9: Output Contract: format and constraints

9.1 Output Contract responsibility boundary: format and constraints

Output Contract is best for:

  • Output format: return JSON such as {status, data, error}
  • Output constraints: do not return passwords or sensitive data
  • Validation rules: status must exist and data must not be null

It is not for:

  • User preferences: the user prefers short answers — put this in memory
  • Global behavior rules: do not delete files — put this in the system prompt

OpenAI Agents SDK guardrails are related to this layer: outputs can be validated and blocked when they violate the contract.

9.2 When Output Contract is the right carrier

Output Contract fits three cases:

  1. Structured output: return {status, data, error} JSON so downstream code can parse it
  2. Safety constraints: never return user passwords or sensitive configuration
  3. Downstream dependency: output must match a schema consumed by an API

9.3 Output Contract mistake: missing contracts break downstream systems

Mistake one: inconsistent format. Sometimes the agent returns JSON, sometimes prose, and the downstream parser fails.

Mistake two: missing validation. The agent returns XML while the downstream API accepts only JSON.

A contract without validation is only a suggestion. Invalid output should be blocked, corrected, or retried.

Capítulo 10: Migration rules: when a rule is repeatedly forgotten, where should it move?

10.1 Migration decision tree

When an agent repeatedly ignores a rule, identify the type first and move it to the right carrier:

Decision branches:

  1. Behavior rule? Do not delete files, do not call unauthorized APIs

    • Yes → move to System Prompt as a global constraint or safety boundary
  2. User preference? prefers short answers, usually communicates in Chinese

    • Yes → move to Long-term Memory for cross-session reuse
  3. Business knowledge? API docs, product manuals, code repository

    • Yes → move to Files/Retrieval for on-demand search
  4. Tool constraint? when to call update_record, when not to call it

    • Yes → move to Tool Description as a miniature behavior controller
  5. Runtime state? step three is done, waiting for user confirmation

    • Yes → move to Runtime State for progress tracking
  6. Output contract? return JSON, include status

    • Yes → move to Output Contract for output validation
  7. Call history? historical tool results or audit logs

    • Yes → move to Trace for post-run analysis

The migration principle is not “put the same text somewhere else”. It is “place each rule in the carrier whose lifecycle and governance match the rule”.

10.2 Migration case 1: from System Prompt to Tool Description

Before migration:

The rule “only modify production data after user confirmation” sits on line 28 of the system prompt. On turn five, the agent still updates the production database without asking.

The system prompt has forty rules: file boundaries, output format, role definition, API snippets, user preferences, and tool constraints. They dilute one another.

After migration:

Move the rule into the update_record tool description:

{
  "name": "update_record",
  "description": "Update a database record. Call this tool only after the user has explicitly confirmed the change. Do not modify production data without authorization. Before calling, require the user to type 'confirm' or 'approve'.",
  "parameters": {...}
}

Reduce the system prompt to ten core rules: role definition, safety boundary, and output contract.

Comparison:

DimensionBeforeAfter
Number of system prompt rules4010
Tool description detailOnly states the functionIncludes when to call, when not to call, and risk boundary
Turn-five complianceIgnoredRequires user confirmation before the call

After migration, the model sees the confirmation requirement at the moment it considers the tool call.

10.3 Migration case 2: from System Prompt to Memory

Before migration:

The rule “the user prefers short answers” sits on line 35 of the system prompt. Later, the user asks for a detailed explanation, but the hardcoded preference still pushes the agent toward short output.

The system prompt treats a user preference as a global rule, even though preferences are dynamic and cross-session.

After migration:

Move the preference into a long-term memory store. At session start, load the user’s memory:

# pseudocode
memory = load_memory(user_id)
if "preference" in memory:
    if memory["preference"] == "short answers":
        conversation_context.append("Use concise answers in this session")
    elif memory["preference"] == "detailed explanations":
        conversation_context.append("Use detailed explanations in this session")

When the user changes the preference, update memory:

update_memory(user_id, {"preference": "detailed explanations"})

Comparison:

DimensionBeforeAfter
Preference locationSystem prompt line 35Long-term memory
Cross-session consistencyHardcoded and inconsistentLoaded dynamically and updateable
After the user changes preferenceOld preference still appliesUpdated memory changes future behavior

Memory is useful only when it can be updated and retired.

Before migration:

An API snippet about the OpenAI Agents SDK tools field is pasted into the system prompt. After an SDK update, the snippet becomes stale and the agent uses the wrong field name.

The system prompt turned versioned documentation into a fixed rule.

After migration:

Move API documentation into a vector store and retrieve the latest relevant document when needed:

# pseudocode
query = "What does the OpenAI Agents SDK tools field contain?"
results = file_search(query, vector_store_id="api_docs_current")

Keep the system prompt focused on role and safety boundaries.

Comparison:

DimensionBeforeAfter
API doc locationSystem prompt lines 12-15Vector store / file search
After version updatesStale snippet remains activeLatest document can be retrieved
Token costAlways in contextRetrieved on demand

Retrieval does not enforce behavior. Pair retrieved API docs with tool schema and validation where needed.

10.5 Migration mistake: rules can still fail after migration

Mistake one: tool description is still too short. If the migrated rule says only what the tool does, the model still lacks invocation boundaries.

Mistake two: memory has no governance. Without expiry and update rules, stale memory becomes a new source of errors.

Mistake three: file search is expected to enforce rules. Retrieval supplies information; instructions, schemas, permissions, and validation enforce behavior.

Migration is the first step. Each layer needs governance: prompt audit, tool-description optimization, memory expiry, file versioning, and state persistence.

Capítulo 11: Engineering audit checklist: an executable context-layering review

11.1 System Prompt audit checklist

Audit a System Prompt with these steps:

  1. Count rules: more than 30 rules suggests migration. More rules usually means more dilution.
  2. Check conflicts: examples include “answer in detail” versus “keep it short”, or “respond quickly” versus “verify thoroughly”.
  3. Classify rule type: behavior rule, user preference, or business knowledge. Preferences should move to memory; business knowledge should move to files.
  4. Find often-forgotten rules: note which rules fail after several turns and choose a target carrier.
  5. Suggest migration: move forgotten rules to tool descriptions or memory, and move documents to files.

11.2 Tool Description audit checklist

Audit Tool Description with these steps:

  1. Check length: under 100 tokens is often too thin; over 500 tokens may waste context budget.
  2. Check six elements: function, input constraints, when to call, when not to call, risk boundary, and return structure.
  3. Review mistaken calls: identify which tools were called at the wrong time and why.
  4. Suggest improvement: add invocation and risk boundaries to thin descriptions; compress overlong descriptions to 100 to 200 tokens.

11.3 Memory system audit checklist

Audit Memory with these steps:

  1. Check memory type: short-term session memory versus long-term cross-session memory.
  2. Check write strategy: what is written, who writes it, and when it is written?
  3. Check expiry strategy: how does memory expire or get updated?
  4. Check memory pollution: identify conflicting preferences across turns.
  5. Suggest governance: define write, update, and expiry policies and use a clear memory store.

11.4 Files/Retrieval audit checklist

Audit Files/Retrieval with these steps:

  1. Check file type: document or rule. Rules should not live only in a knowledge base.
  2. Check retrieval timing: when does retrieval run, and what target is it searching?
  3. Check document updates: if SDK docs change, the vector store should update too.
  4. Check retrieved results: did retrieval help, or did it only add noise?
  5. Suggest improvement: move rules to instructions or tool descriptions, and version the document store.

11.5 Runtime State audit checklist

Audit Runtime State with these steps:

  1. Check state type: progress, branch choice, or pending approval.
  2. Check persistence: can the task resume after interruption?
  3. Check state pollution: are multiple branches mixed together?
  4. Suggest improvement: add checkpointing or another persistence mechanism.

11.6 Output Contract audit checklist

Audit Output Contract with these steps:

  1. Check output format: JSON, text, XML, or another downstream format.
  2. Check validation: can downstream code parse it reliably?
  3. Check safety constraints: passwords and sensitive configuration must not appear in output.
  4. Suggest improvement: add output validation through guardrails or equivalent checks.

11.7 Trace audit checklist

Audit Trace with these steps:

  1. Check trace length: is historical tool output being loaded into the current context?
  2. Check trace purpose: audit or decision input. Trace should support review, not crowd active reasoning.
  3. Check trace clearing: move old tool results into trace and keep only current results active.
  4. Suggest improvement: define tool-result clearing and audit-log retention.

Capítulo 13: Next step and further reading

13.1 Upstream article in this series

AI Agent Engineering 2026: choosing from LangGraph to OpenAI Agents SDK covers framework selection. This article follows it by focusing on context layering. Once the framework is chosen, the next design problem is context architecture.

This section keeps the boundary at context layering. For deeper topics, continue here:

  • Agent memory system design: Agent memory system design: from session to long-term memory — memory types, storage choices, and governance strategy
  • Agent tool calling in practice: Agent tool calling in practice — tool definition, invocation, validation, and governance
  • DeepAgents architecture: DeepAgents architecture — upstream concepts around planning tools, file systems, and system prompts

13.3 Series next steps

After context layering, later articles in the series can go deeper into each governance layer:

  • Human approval (HITL): when human intervention is needed to prevent mistaken actions
  • Cost budgeting: token consumption and context budget planning for each layer
  • Permission model: tool permissions, data access rules, and tenant isolation
  • State machine: task progress, branch choice, and error recovery
  • Evaluation dataset: how to build benchmarks for context layering
  • Launch checklist: a production audit before moving from prototype to live agent

Conclusion

Context engineering does not end when you put rules into a prompt. It means actively designing the responsibility boundary, lifecycle, and governance policy for each context carrier.

The core framework has eight carriers: System Prompt, Memory, Files, Tools, State, Trace, Output Contract, and User Task. The migration decision tree asks whether a failing rule is a behavior rule, user preference, business document, tool constraint, runtime state, output contract, or call history. The audit checklist turns those distinctions into a practical review process.

Start with the System Prompt audit. Count the rules, look for conflicts, and decide which ones belong in Tool Description, Memory, or Files. Do the layering before turn five is where the forgotten rule turns into a production incident.

Como dividir o contexto de um agente

Separar prompts, memory, files, tools e state em portadores de contexto com responsabilidades claras.

⏱️ Estimated time: 30 min

  1. 1

    Step 1: Liste regras e fontes

    Coloque lado a lado system prompt, regras de desenvolvimento, tarefa do usuário, descrições de tools, material recuperado e requisitos de saída.
  2. 2

    Step 2: Classifique cada item

    Decida se é limite de comportamento, preferência, documento de negócio, restrição de ferramenta, estado, contrato ou trace.
  3. 3

    Step 3: Mova conhecimento duradouro ou externo

    Leve preferências entre sessões para memory e documentação longa ou mutável para retrieval/file search.
  4. 4

    Step 4: Ajuste limites de tools e state

    Escreva quando chamar, quando não chamar e riscos em tool descriptions; leve progresso e aprovações para runtime state.
  5. 5

    Step 5: Teste com tarefas reais

    Use tarefas multi-turno, chamadas erradas e recuperação após interrupção.

FAQ

O que é context engineering para agentes?
É gerenciar por responsabilidade a informação visível ao modelo: prompt, memory, retrieval, tool schema, runtime state, trace e output contract.
Por que um agente esquece regras no system prompt?
Porque o prompt não é o único portador de contexto nem um sistema de permissões. Regras, tarefas, documentos, tools e estado competem na mesma janela.
Qual é a diferença entre system prompt e memory?
O system prompt limita a execução atual; memory guarda preferências e fatos reutilizáveis entre sessões.
Arquivos vão no prompt ou no file search?
Conteúdo curto e estável pode ir no prompt; documentos longos ou mutáveis combinam melhor com retrieval/file search.
O que uma tool description deve conter?
Propósito, restrições de entrada, quando chamar, quando não chamar, riscos e estrutura de retorno.
O que fazer quando regras falham com frequência?
Não aumente apenas o prompt. Classifique a regra e mova para instructions, schema, retrieval, state ou output contract.

25 min de leitura · Publicado em: 11 set 2026 · Atualizado em: 11 set 2026

Comentários

Entre com GitHub para comentar

Easton BlogEaston Blog