### Attention Anchoring Example Source: https://contextpatterns.com/patterns/attention-anchoring Comparison of unoptimized context ordering versus a sandwich structure that anchors critical information at the start and end. ```text [Troubleshooting guide: 500 lines] [Ticket history: 200 lines] [User's current issue: 50 lines] [System logs: 300 lines] ``` ```text ## Current Issue The user cannot export reports to PDF. Error: "Export failed: timeout after 30s." Started after the v2.3 update. [Troubleshooting guide: 500 lines] [Ticket history: 200 lines] [System logs: 300 lines] ## Summary Issue is PDF export timeout in v2.3. Investigate export service timeout config and database query performance. ``` -------------------------------- ### Context Engineering Approach Example Source: https://contextpatterns.com/guides/what-is-context-engineering A prompt enhanced with specific codebase patterns and requirements to ensure the generated code aligns with existing conventions. ```text Current codebase patterns: - Validation uses pydantic schemas in models.py - Password validation requires 8+ chars, one number, one special - Email validation uses the email-validator library - Error handling returns HTTP 422 with detail dict Task: Write a validate_user_input function for auth.py that follows these patterns. ``` -------------------------------- ### Refactoring State Scratchpad Example Source: https://contextpatterns.com/patterns/scratchpad A sample scratchpad structure for a coding agent, containing a task plan, key decisions, and open questions. ```markdown ## Refactoring State - [x] auth/tokens.py - switched to RS256, token expiry 1h - [x] auth/sessions.py - session store moved to Redis - [x] auth/middleware.py - updated to use new token format - [x] api/login.py - uses new session store - [ ] api/protected.py - needs token validation update - [ ] api/admin.py - needs role-based checks - [ ] tests/test_auth.py - rewrite for new token format - [ ] docs/auth.md - update API documentation ## Decisions - Token format: RS256 JWT (chosen over HS256 for key rotation) - Error codes: 401 for expired, 403 for insufficient role - Session TTL: 24h with sliding window ## Open questions - Should admin endpoints use a separate token scope? ``` -------------------------------- ### Prompt Engineering Approach Example Source: https://contextpatterns.com/guides/what-is-context-engineering A basic prompt requesting a function without providing codebase-specific context. ```text Write a function to validate user input that checks email format and password strength. ``` -------------------------------- ### Define Good Tool Definitions Source: https://contextpatterns.com/patterns/tool-descriptions Examples of descriptive tool definitions that provide workflow context, constraints, and expected input/output relationships. ```python def query_db(sql): """Execute a read-only SQL query against the analytics database. Use for metrics, counts, aggregations, and lookups by ID. Do NOT use for writes or schema info (use describe_tables instead). Returns: JSON array of matching rows.""" def create_chart(data, chart_type): """Create a visualization from query results. Use after query_db when the user wants to see data visually. chart_type: 'bar' | 'line' | 'pie' | 'scatter'. Returns: URL to the generated chart image.""" def send_email(to, subject, body): """Send results to a user. Use ONLY after analysis is complete with results to share. Do not send test messages or debugging output. Requires: valid email, non-empty subject and body.""" ``` -------------------------------- ### Define Bad Tool Definitions Source: https://contextpatterns.com/patterns/tool-descriptions Examples of minimal tool definitions that force the model to guess functionality. ```python def query_db(sql): """Run a SQL query.""" def create_chart(data, type): """Create a chart.""" def send_email(to, subject, body): """Send an email.""" ``` -------------------------------- ### Coding Agent Memory File Example Source: https://contextpatterns.com/patterns/write-outside A sample markdown file used by a coding agent to store project conventions, architecture decisions, and learned constraints. ```markdown ## Project - Python 3.12, FastAPI, PostgreSQL - Monorepo with shared libs in /packages - Tests use pytest with factory_boy fixtures ## Conventions - Type hints on all public functions - Database queries go through the repository pattern - Never use raw SQL outside /db/migrations ## Learned - The auth module has a circular import if you import directly; use the interface - Rate limiter tests are flaky on CI; needs Redis mock, not real connection - User.email has a unique constraint that the ORM doesn't enforce at the model level ``` -------------------------------- ### Compare Tool Description Quality Source: https://contextpatterns.com/patterns/tool-descriptions Demonstrates the difference between a vague tool description and one that provides clear scope, triggers, and boundaries. ```python def search_documents(query: str): """Search for documents matching the query.""" ``` ```python def search_documents(query: str): """Search the internal knowledge base for policies, procedures, and FAQs. Use when the user asks about company processes or specific procedures. Returns top 5 results with excerpts. Does NOT search code repositories or customer data.""" ``` -------------------------------- ### Implement Sliding Window Memory with LangChain Source: https://contextpatterns.com/patterns/temporal-decay Uses a fixed-size window to keep only the most recent N turns in the active context. ```python from langchain.memory import ConversationBufferWindowMemory memory = ConversationBufferWindowMemory(k=5, return_messages=True) ``` -------------------------------- ### Build Tiered Context with Summarization Source: https://contextpatterns.com/patterns/temporal-decay Combines full-fidelity recent messages with a compressed summary of older messages to balance detail and context size. ```python def build_tiered_context(messages, recent_n=5, summary_n=20): recent = messages[-recent_n:] middle = messages[-summary_n:-recent_n] if middle: summary = llm.complete( "Summarize this conversation history in 3-5 sentences, " "noting any decisions or constraints that still apply:\n" + format_messages(middle) ) return [SystemMessage(f"Earlier context:\n{summary}")] + recent return recent ``` -------------------------------- ### Define a JSON Schema for Bug Triage Source: https://contextpatterns.com/patterns/schema-steering A schema definition for classifying bug reports with specific fields, enums, and constraints to ensure structured output. ```json { "type": "object", "properties": { "severity": { "type": "string", "enum": ["critical", "high", "medium", "low"], "description": "Impact on system functionality" }, "root_cause": { "type": "string", "description": "The underlying technical cause" }, "affected_component": { "type": "string", "description": "Which system component is affected" }, "confidence": { "type": "number", "minimum": 0, "maximum": 1, "description": "How confident the classification is" } }, "required": ["severity", "root_cause", "affected_component", "confidence"] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.