mcikalmerdeka commited on
Commit
400e6ac
·
1 Parent(s): 4afc8ce

update README.md to enhance clarity and structure, emphasizing the principles of context engineering and providing detailed usage instructions for the visualizer

Browse files
Files changed (1) hide show
  1. README.md +319 -363
README.md CHANGED
@@ -1,505 +1,461 @@
1
  # Context Engineering Visualizer
2
 
3
- A visual demonstration of **context engineering** principles in LLM-based agents. This project shows how information flows into an agent's context window before inference, making the abstract concept of "context engineering" concrete and understandable.
4
 
5
- ## What is Context Engineering?
6
 
7
- **Context engineering** is the practice of deliberately deciding:
8
 
9
- - **What information** an AI model sees
10
- - **When** it sees it
11
- - **In what format** it's presented
12
 
13
- Unlike prompt engineering (which focuses on *how you ask*), context engineering shapes *what the model understands*.
14
 
15
- ## Features
 
 
 
 
 
16
 
17
- This visualizer demonstrates the **5 key context layers**:
18
 
19
- 1. 🎯 **System Instructions** - Stable behavioral guidelines
20
- 2. 💬 **Conversation History** - Short-term memory with smart truncation
21
- 3. 📚 **Retrieved Knowledge (RAG)** - Relevant documents from vector store
22
- 4. 📝 **User Query** - Current user intent
23
- 5. 🔧 **Available Tools** - External capabilities the agent can use
24
 
25
- ## Project Structure
26
 
27
- ```
28
- context-engineering-visualizer/
29
- ├── main.py # Main application with agent and visualizer
30
- ├── pyproject.toml # Dependencies (uv package manager)
31
- ├── README.md # This file
32
- └── .env # Your OpenAI API key (create from .env.example)
33
- ```
34
 
35
- ## Installation
 
 
 
 
36
 
37
- ### 1. Clone & Setup
38
 
39
- ```bash
40
- # Make sure you have Python 3.12+ installed
41
- python --version
42
-
43
- # Install uv if you haven't (fast Python package manager)
44
- pip install uv
45
- ```
46
 
47
- ### 2. Install Dependencies
48
 
49
- ```bash
50
- # Using uv (recommended)
51
- uv sync
52
 
53
- # Or using pip
54
- pip install -e .
55
  ```
56
 
57
- ### 3. Set Up API Key
58
 
59
- Create a `.env` file in the project root:
60
 
61
- ```bash
62
- OPENAI_API_KEY=your-api-key-here
63
- ```
64
-
65
- Get your API key from: https://platform.openai.com/api-keys
66
 
67
- ## Usage
 
 
68
 
69
- ### Demo Mode (Recommended First)
 
70
 
71
- Run pre-built scenarios to see context engineering in action:
 
72
 
73
- ```bash
74
- python main.py
75
  ```
76
 
77
- This will walk you through 3 scenarios:
78
 
79
- 1. RAG-based query
80
- 2. Query requiring tool use
81
- 3. Query using conversation context
82
 
83
- ### Interactive Mode
84
-
85
- Chat with the agent and see real-time context visualization:
86
-
87
- ```bash
88
- python main.py interactive
 
 
89
  ```
90
 
91
- ### Example Queries to Try for the interactive mode
92
 
93
- **Basic Knowledge Questions:**
94
 
95
- - "What is Net Revenue?"
96
- - "What is Average Order Value?"
97
- - "Explain Customer Lifetime Value"
98
- - "What's the difference between gross and net revenue?"
99
- - "What is churn rate?"
100
-
101
- **Tool Usage (Calculations):**
 
 
 
 
 
 
 
 
 
102
 
103
- - "Calculate AOV if revenue is $100000 and orders are 2000"
104
- - "Calculate conversion rate with 500 conversions from 10000 visitors"
105
- - "Calculate churn rate if 50 out of 1000 customers left"
106
- - "What time is it?"
107
 
108
- **Using Conversation Context:**
109
 
110
- - Ask: "What is AOV?"
111
- - Then: "Can you calculate it for $50000 revenue and 500 orders?"
112
- - Then: "What about with 750 orders?" ← *Uses previous context!*
113
 
114
- **Complex Queries:**
 
 
 
 
 
 
115
 
116
- - "I have $80000 in revenue from 1200 orders. What's my AOV and is it good?"
117
- - "Calculate churn rate if 120 out of 2400 customers left, and explain what it means"
118
 
119
- ## What Makes This "Context Engineering"?
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
- ### NOT Just Prompt Engineering
122
 
123
- ```python
124
- # Prompt engineering
125
- prompt = "Calculate AOV using this formula..."
126
 
127
- # Context engineering
128
- context = {
129
- system: "You are a data analyst...",
130
- history: [last_4_messages],
131
- knowledge: retrieve_relevant(query),
132
- query: user_question,
133
- tools: [calculate_metric, get_time]
134
- }
135
  ```
136
 
137
- ### The Key Difference
138
 
139
- | Aspect | Prompt Engineering | Context Engineering |
140
- | ------------------ | ------------------ | ------------------------- |
141
- | **Focus** | Wording | Information flow |
142
- | **Scope** | Single message | Entire system |
143
- | **Strategy** | Optimize phrasing | Optimize context assembly |
144
- | **Tools** | Text tricks | RAG, memory, tools |
145
 
146
- ## How It Works
147
 
148
- ### Context Engineering Principles Demonstrated
 
 
149
 
150
- #### 1. **Relevance**
 
 
151
 
152
- - Only retrieves top 2 most relevant documents (not entire knowledge base)
153
- - Keeps only last 4 conversation messages (prevents context bloat)
154
- - Each layer serves a specific purpose
155
 
156
- #### 2. **Structure**
157
 
158
- - Clear separation between system instructions and data
159
- - Structured format: Context → History → Query
160
- - Models perform better with organized information
161
 
162
- #### 3. **Timing**
163
 
164
- - Knowledge retrieved *after* user query (not preloaded)
165
- - History summarized *before* sending to model
166
- - Tools called only when needed
 
167
 
168
- #### 4. **Consistency**
169
 
170
- - Stable system prompt across all interactions
171
- - Low temperature (0) for predictable behavior
172
- - Reusable context assembly pattern
173
 
174
- ### Common Patterns You'll Notice
 
 
 
 
175
 
176
- **Pattern 1: Relevance Filtering**
177
 
178
- - Doesn't send all 8 knowledge documents
179
- - Only sends top 2 relevant ones
180
- - Saves tokens, improves focus
181
 
182
- **Pattern 2: Smart Truncation**
183
 
184
- - Conversation history limited to 4 messages
185
- - Keeps recent context
186
- - Prevents token overflow
 
187
 
188
- **Pattern 3: Layer Separation**
189
 
190
- - Instructions ≠ Data ≠ Query
191
- - Clear boundaries help model
192
- - Structured input → better output
193
 
194
- **Pattern 4: Dynamic Retrieval**
195
 
196
- - Knowledge fetched per-query
197
- - Not pre-loaded
198
- - Timing matters
199
 
200
- ### Understanding the Context Layers
 
 
201
 
202
- **1. System Instructions (Stable)**
203
 
204
- - Same every time
205
- - Defines agent behavior
206
- - Sets output style
207
 
208
- **2. Conversation History (Dynamic)**
209
 
210
- - Last 4 messages only
211
- - Prevents context bloat
212
- - Enables follow-up questions
213
 
214
- **3. Retrieved Knowledge (Relevant)**
215
 
216
- - Top N similar documents
217
- - Retrieved via semantic search
218
- - Based on current query
219
 
220
- **4. User Query (Current)**
221
 
222
- - Your actual question
223
- - Fresh every time
 
224
 
225
- **5. Available Tools (Capabilities)**
226
 
227
- - Functions agent can call
228
- - Descriptions help model decide
229
- - Executed when needed
230
 
231
- ### Visualization Output
 
 
 
 
 
232
 
233
- Each query shows:
234
 
235
- ```
236
- ================================================================================
237
- CONTEXT WINDOW VISUALIZATION
238
- ================================================================================
239
-
240
- 1. SYSTEM INSTRUCTIONS
241
- Tokens: 45 (15.2%)
242
- [███████ ]
243
- Content:
244
- You are a data analyst assistant...
245
-
246
- 2. CONVERSATION HISTORY
247
- Tokens: 67 (22.6%)
248
- [███████████ ]
249
- Content:
250
- User: What is AOV?...
251
-
252
- 3. RETRIEVED KNOWLEDGE (RAG)
253
- Tokens: 89 (30.1%)
254
- [███████████████ ]
255
- Content:
256
- - AOV (Average Order Value) is calculated...
257
-
258
- 4. USER QUERY
259
- Tokens: 32 (10.8%)
260
- [█████ ]
261
- Content:
262
- Calculate AOV if revenue is $50000...
263
-
264
- 5. AVAILABLE TOOLS
265
- Tokens: 63 (21.3%)
266
- [██████████ ]
267
- Content:
268
- - calculate_metric: Calculate a business metric...
269
-
270
- ================================================================================
271
- TOTAL CONTEXT TOKENS: 296
272
- ================================================================================
273
- ```
274
 
275
- **Understanding the Token Bar:**
276
 
277
- ```
278
- [███████████████ ]
 
279
  ```
280
 
281
- - Shows percentage of total context
282
- - Longer bar = more tokens
283
- - Helps visualize context budget
284
 
285
- ## Architecture & Information Flow
286
 
287
- ### Context Engineering Flow
288
-
289
- ```mermaid
290
- graph TD
291
- A["User Input: Calculate AOV for my data"] --> B["Context Engineering Layer"]
292
-
293
- B --> C1["1. System Instructions"]
294
- B --> C2["2. Conversation History"]
295
- B --> C3["3. Retrieved Knowledge RAG"]
296
- B --> C4["4. User Query"]
297
- B --> C5["5. Available Tools"]
298
-
299
- C1 --> D["System Instructions:<br/>You are a data analyst assistant<br/>Use provided context to answer<br/>Always explain reasoning"]
300
-
301
- C2 --> E["Last 4 Messages Only<br/>Smart Truncation"]
302
- E --> F["User: What is gross revenue?<br/>AI: Gross revenue is total sales..."]
303
-
304
- C3 --> G["Vector Store FAISS"]
305
- G -->|"Semantic Search"| H["Top 2 Relevant Documents:<br/>AOV = revenue / orders<br/>Net Revenue = gross - refunds"]
306
-
307
- C4 --> I["Current Question:<br/>Calculate AOV for my data"]
308
-
309
- C5 --> J["Tools:<br/>calculate_metric<br/>get_current_time"]
310
-
311
- D --> K["Assembled Context"]
312
- F --> K
313
- H --> K
314
- I --> K
315
- J --> K
316
-
317
- K --> L["Language Model<br/>GPT-4.1-mini"]
318
- L -->|"Complete context with<br/>clear structure"| M["Inference / Reasoning"]
319
-
320
- M --> N["Agent Response"]
321
- N --> O["Based on definition, AOV is<br/>calculated as total revenue<br/>divided by number of orders<br/>Calls calculate_metric tool<br/>Result: AOV = 66.67"]
322
  ```
323
 
324
- ### Context Engineering Principles
325
 
326
- **1. Relevance (What to Include)**
327
 
 
 
 
328
  ```
329
- ❌ BAD: Dump entire knowledge base (1000+ docs, 10,000 tokens)
330
- ✅ GOOD: Retrieve top-2 most relevant docs (200 tokens)
331
 
332
- Token Savings: 10,000 200 tokens (50x reduction!)
333
- ```
334
 
335
- **2. Structure (How to Organize)**
336
 
 
 
 
337
  ```
338
- ❌ BAD: "You are helpful. User said X. Documents say Y. Calculate Z."
339
- ✅ GOOD: Clear layers with separation:
340
- System Instructions: [...]
341
- Conversation History: [...]
342
- Retrieved Knowledge: [...]
343
- Current Query: [...]
344
- ```
345
-
346
- **3. Timing (When to Retrieve)**
347
 
348
- ```
349
- Timeline:
350
- 1. User asks question
351
- 2. Retrieve relevant knowledge (not before!)
352
- 3. Fetch conversation history
353
- 4. Assemble context
354
- 5. Send to model
355
-
356
- ⚠️ Don't pre-load all possible context!
357
- ```
358
 
359
- **4. Consistency (Stable Patterns)**
360
 
361
- ```
362
- Same system prompt every time → predictable behavior
363
- Low temperature (0) consistent responses
364
- ✓ Fixed context structure → reliable reasoning
365
  ```
366
 
367
- ### Token Efficiency Comparison
368
 
369
- | Approach | Total Tokens | Breakdown | Cost per Query | Performance |
370
- | ---------------------------------- | ------------ | ----------------------------------------------------------------------------------------------- | -------------- | ------------------------------ |
371
- | **Bad Context Engineering** | 15,000 | All docs: 12,000``Full history: 2,000``System+Query: 1,000 | $0.15 | Model struggles with noise |
372
- | **Good Context Engineering** | 500 | System: 50``Last 4 msgs: 150``Top-2 docs: 200``Query: 50``Tools: 50 | $0.005 | Model focuses, performs better |
373
 
374
- **Result: 30x cheaper + better performance!**
375
 
376
- ## Code Highlights
377
-
378
- ### Agent Architecture
379
 
380
  ```python
381
  class ContextEngineeringAgent:
382
- def __init__(self):
383
- self.llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
384
- self.knowledge_base = KnowledgeBase() # RAG component
385
- self.memory = ConversationMemory() # History management
386
- self.visualizer = ContextVisualizer() # Visualization
387
- self.agent = create_agent(
388
- model=self.llm,
389
- tools=[calculate_metric, get_current_time],
390
- system_prompt=self.system_prompt
391
- )
392
- ```
393
-
394
- ### Context Assembly
395
-
396
- The key insight is **explicit context construction** before inference:
397
-
398
- ```python
399
- context_message = f"""Context from Knowledge Base:
400
- {retrieved_context}
401
 
402
  Previous Conversation:
403
  {history_text}
404
 
405
  Current Question:
406
  {user_query}"""
407
-
408
- result = self.agent.invoke({
409
- "messages": [{"role": "user", "content": context_message}]
410
- })
411
  ```
412
 
413
- ## Technologies Used
414
 
415
- - **LangChain** - Agent framework
416
- - **OpenAI GPT-4.1-mini** - Language model
417
- - **FAISS** - Vector store for RAG
418
- - **OpenAI Embeddings** - Text embeddings
419
- - **Python 3.12+** - Programming language
 
 
 
 
 
 
 
 
420
 
421
- ## Common Context Engineering Mistakes (That This Avoids)
422
 
423
- **Dumping entire documents** ✅ Retrieve only top-k relevant chunks
424
- ❌ **Sending full chat history** → ✅ Smart truncation to recent messages
425
- ❌ **Mixing instructions with data** → ✅ Clear layer separation
426
- ❌ **No token awareness** → ✅ Token estimation and visualization
427
- ❌ **Static context** → ✅ Dynamic retrieval based on query
428
 
429
- ## Troubleshooting
 
 
 
 
 
 
 
 
 
430
 
431
- ### "ModuleNotFoundError"
432
 
433
- ```bash
434
- # Install dependencies
435
- uv sync
436
- # or
437
- pip install -e .
438
- ```
439
 
440
- ### "OpenAI API Error"
 
 
 
441
 
442
- - Check `.env` file exists
443
- - Verify API key is correct
444
- - Ensure key starts with `sk-`
445
 
446
- ### "RateLimitError"
447
 
448
- - You've hit OpenAI rate limit
449
- - Wait a moment and try again
450
- - Consider upgrading OpenAI plan
 
 
 
 
 
 
 
 
 
 
 
 
451
 
452
- ### No output shown
453
 
454
- - Check API key has credits
455
- - Verify internet connection
456
- - Look for error messages
457
 
458
- ## Tips for Best Results
 
 
 
 
 
 
459
 
460
- ### Writing Good Queries
461
 
462
- ✅ "Calculate AOV for $50000 revenue and 500 orders"
463
- "do the aov thing"
 
 
 
 
 
 
 
464
 
465
- "What's the difference between gross and net revenue?"
466
- ❌ "revenue?"
467
 
468
- ### Follow-up Questions
 
 
 
 
 
469
 
470
- After asking about a metric:
471
 
472
- - "Can you calculate it for my data?"
473
- - "What about with different numbers?"
474
- - "Compare that to industry average"
475
 
476
- ### Observing Context Flow
 
 
 
477
 
478
- Watch how:
479
 
480
- - RAG retrieves different docs per query
481
- - History accumulates over conversation
482
- - Tools get called when numbers are involved
483
- - Token distribution changes
 
484
 
485
- ## Key Insights
486
 
487
- 1. **Context is multi-layered** - Not just your prompt
488
- 2. **Less is often more** - Relevant beats comprehensive
489
- 3. **Structure matters** - Organization helps models
490
- 4. **Dynamic beats static** - Assemble per-query
491
- 5. **Tokens cost money** - Engineering saves budget
492
 
493
- ## Next Steps
 
 
 
494
 
495
- Want to extend this project?
496
 
497
- - Add token cost tracking ($ per query)
498
- - Implement context compression techniques
499
- - Add more sophisticated memory (summarization)
500
- - Create a web UI with real-time visualization
501
- - Compare context strategies (with/without RAG, different window sizes)
502
 
503
  ## Contributing
504
 
505
- This is a learning/demo project. Feel free to fork and adapt for your own articles or projects!
 
 
 
 
 
1
  # Context Engineering Visualizer
2
 
3
+ A professional educational tool that demonstrates how information flows into an AI agent's context window before inference. Built with LangChain and Gradio.
4
 
5
+ > **Context engineering is the practice of deliberately deciding what information an AI model sees, when it sees it, and in what format.**
6
 
7
+ ## What Is Context Engineering?
8
 
9
+ Most developers only focus on prompt engineering (optimizing the wording of queries). But the real power comes from **context engineering**: designing the entire information flow into your model.
 
 
10
 
11
+ ### Context Engineering vs. Prompt Engineering
12
 
13
+ | Aspect | Prompt Engineering | Context Engineering |
14
+ | ------------------ | ------------------ | ------------------------- |
15
+ | **Focus** | Wording | Information flow |
16
+ | **Scope** | Single message | Entire system |
17
+ | **Strategy** | Optimize phrasing | Optimize context assembly |
18
+ | **Tools** | Text tricks | RAG, memory, tools |
19
 
20
+ Think of it this way:
21
 
22
+ > **Prompt engineering shapes how you ask. Context engineering shapes what the model understands.**
 
 
 
 
23
 
24
+ ## What Goes Into "Context"?
25
 
26
+ When you call an LLM, you're not just sending a prompt. You're sending a **multi-layered context window**:
 
 
 
 
 
 
27
 
28
+ 1. **System Instructions**: Stable behavioral guidelines
29
+ 2. **Conversation History**: Recent interactions for continuity
30
+ 3. **Retrieved Knowledge (RAG)**: Relevant documents from a knowledge base
31
+ 4. **User Query**: The current question or request
32
+ 5. **Available Tools**: External functions the agent can use
33
 
34
+ Most developers only optimize layer #4 (the user query). **Context engineering optimizes all five layers.**
35
 
36
+ ## The Four Principles of Context Engineering
 
 
 
 
 
 
37
 
38
+ ### 1. Relevance: Only Include What Helps
39
 
40
+ ```python
41
+ # Bad: Dump everything
42
+ docs = vectorstore.get_all_documents() # 1000+ docs, 50k tokens
43
 
44
+ # Good: Retrieve top-k relevant
45
+ docs = retriever.invoke(query, k=2) # 2 docs, ~100 tokens
46
  ```
47
 
48
+ More context ≠ better answers. Noise hurts performance and costs money.
49
 
50
+ ### 2. Structure: Organize Information Clearly
51
 
52
+ ```python
53
+ # Bad: Mix everything together
54
+ context = f"{system_prompt} {docs} {history} {query} {tools}"
 
 
55
 
56
+ # Good: Clear layers
57
+ context = f"""System Instructions:
58
+ {system_prompt}
59
 
60
+ Conversation History:
61
+ {history}
62
 
63
+ Retrieved Knowledge:
64
+ {docs}
65
 
66
+ Current Question:
67
+ {query}"""
68
  ```
69
 
70
+ Models perform better when they can distinguish between different types of information.
71
 
72
+ ### 3. Timing: Retrieve Information When Needed
 
 
73
 
74
+ ```python
75
+ # Bad: Pre-load everything
76
+ def __init__(self):
77
+ self.all_docs = load_entire_database() # Loaded once
78
+
79
+ # Good: Dynamic retrieval
80
+ def process_query(self, query: str):
81
+ docs = self.retriever.invoke(query) # Retrieved per-query
82
  ```
83
 
84
+ Don't front-load information. Fetch what you need, when you need it.
85
 
86
+ ### 4. Consistency: Use Stable Patterns
87
 
88
+ ```python
89
+ # Stable system prompt
90
+ self.system_prompt = "You are a data analyst assistant..."
91
+
92
+ # Predictable temperature
93
+ self.llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
94
+
95
+ # Reusable context assembly
96
+ def assemble_context(self, query):
97
+ return {
98
+ "system": self.system_prompt,
99
+ "history": self.memory.get_recent(n=4),
100
+ "knowledge": self.retrieve(query, k=2),
101
+ "query": query
102
+ }
103
+ ```
104
 
105
+ Consistency reduces randomness and improves reliability.
 
 
 
106
 
107
+ ## Features
108
 
109
+ This visualizer demonstrates all four principles in action:
 
 
110
 
111
+ - **Interactive Chat Interface**: Clean, modern chatbot UI with conversation history
112
+ - **Visual Context Breakdown**: Custom stacked container visualization showing proportional token distribution
113
+ - **RAG Integration**: Demonstrates retrieval-augmented generation with a knowledge base
114
+ - **Conversation Memory**: Smart truncation of conversation history
115
+ - **Tool Usage**: Shows how agents use external tools for calculations
116
+ - **Real-time Token Tracking**: See exactly how tokens are distributed across context layers
117
+ - **Collapsible Sidebar**: Settings and example questions in an easy-to-access sidebar
118
 
119
+ ## Project Structure
 
120
 
121
+ ```
122
+ context-engineering-visualizer/
123
+ ├── app/
124
+ │ ├── __init__.py
125
+ │ ├── agent.py # Main agent implementation
126
+ │ ├── visualizer.py # Context visualization logic
127
+ │ ├── memory.py # Conversation memory management
128
+ │ ├── knowledge.py # RAG knowledge base
129
+ │ ├── tools.py # Agent tools
130
+ │ └── ui.py # Gradio interface
131
+ ├── config/
132
+ │ ├── __init__.py
133
+ │ └── settings.py # Application configuration
134
+ ├── main.py # Entry point
135
+ ├── pyproject.toml
136
+ └── README.md
137
+ ```
138
 
139
+ ## Installation
140
 
141
+ 1. Clone the repository:
 
 
142
 
143
+ ```bash
144
+ git clone https://github.com/mcikalmerdeka/context-engineering-visualizer
145
+ cd context-engineering-visualizer
 
 
 
 
 
146
  ```
147
 
148
+ 2. Install dependencies using uv:
149
 
150
+ ```bash
151
+ uv sync
152
+ ```
 
 
 
153
 
154
+ 3. Create a `.env` file with your OpenAI API key:
155
 
156
+ ```
157
+ OPENAI_API_KEY=your_api_key_here
158
+ ```
159
 
160
+ ## Usage
161
+
162
+ Run the Gradio application:
163
 
164
+ ```bash
165
+ python main.py
166
+ ```
167
 
168
+ The interface will launch at `http://127.0.0.1:7860`
169
 
170
+ ## Interface Overview
 
 
171
 
172
+ The Gradio interface features:
173
 
174
+ 1. **Collapsible Sidebar**: Contains settings and sequential example questions organized by scenario
175
+ 2. **Chat Interface**: Main conversation area with user messages on the right, assistant on the left
176
+ 3. **Context Window Breakdown**: Visual stacked container showing proportional token distribution
177
+ 4. **Detailed Layer Contents**: Expandable section with full content of each context layer
178
 
179
+ ### Visual Context Breakdown
180
 
181
+ The visualizer uses a custom stacked container visualization (similar to a database cylinder) where each layer's height is proportional to its token usage. When you ask a question, you'll see:
 
 
182
 
183
+ - **System Instructions** (Blue): Stable behavioral guidelines
184
+ - **Conversation History** (Purple): Recent messages for context
185
+ - **Retrieved Knowledge** (Green): Relevant documents from RAG
186
+ - **User Query** (Orange): Your current question
187
+ - **Available Tools** (Red): Functions the agent can call
188
 
189
+ Each section displays:
190
 
191
+ - Layer name and purpose
192
+ - Token count and percentage
193
+ - Proportional visual representation
194
 
195
+ Notice what's happening:
196
 
197
+ - Only **2 relevant documents** retrieved (not the entire knowledge base)
198
+ - **Clear separation** between instructions, data, and query
199
+ - **Token-efficient** design
200
+ - **Tools available** but only called when needed
201
 
202
+ The model receives exactly what it needs, no more, no less.
203
 
204
+ ### Scenario Examples
 
 
205
 
206
+ The interface includes four sequential scenarios in the sidebar to help you understand context engineering:
207
 
208
+ **Scenario 1: Understanding AOV (Average Order Value)**
 
 
209
 
210
+ 1. What is Average Order Value and how is it calculated?
211
+ 2. Calculate the AOV if total revenue is $50000 and we had 500 orders
212
+ 3. What if we had 700 orders with the same revenue instead?
213
 
214
+ **Scenario 2: Conversion Rate Analysis**
215
 
216
+ 1. What is Conversion Rate?
217
+ 2. Calculate conversion rate with 250 conversions and 10000 visitors
218
+ 3. How would the rate change if we got 400 conversions?
219
 
220
+ **Scenario 3: Understanding Revenue Metrics**
221
 
222
+ 1. What is the difference between gross and net revenue?
223
+ 2. If gross revenue is $100000 with $15000 in refunds and $5000 in discounts, what's the net revenue?
 
224
 
225
+ **Scenario 4: Churn Rate**
226
 
227
+ 1. Explain what Churn Rate means
228
+ 2. Calculate churn rate if we lost 50 customers out of 1000 total customers
 
229
 
230
+ These scenarios demonstrate:
231
 
232
+ - **RAG retrieval**: Fetching relevant knowledge
233
+ - **Tool usage**: Calling calculation functions
234
+ - **Context awareness**: Using conversation history for follow-up questions
235
 
236
+ The third question in each scenario showcases context engineering - the agent understands follow-ups because we engineered the context to include relevant history.
237
 
238
+ ## Using the Interface
 
 
239
 
240
+ 1. **Open the sidebar** to see settings and example questions
241
+ 2. **Enable/disable context visualization** using the checkbox
242
+ 3. **Follow the sequential scenarios** to understand how context engineering works
243
+ 4. **Ask your own questions** about business metrics
244
+ 5. **Expand the Context Window Breakdown** to see the visual token distribution
245
+ 6. **View detailed layer contents** by expanding the nested accordion
246
 
247
+ The interface is designed to be educational - each interaction shows you exactly how the context is assembled before being sent to the model.
248
 
249
+ ## Common Context Engineering Mistakes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
 
251
+ ### Mistake 1: Dumping Entire Documents
252
 
253
+ ```python
254
+ # Don't do this
255
+ context = "\n".join(all_documents) # 50,000 tokens
256
  ```
257
 
258
+ **Fix:** Use semantic search to retrieve only top-k relevant chunks.
 
 
259
 
260
+ ### Mistake 2: Sending Full Chat History
261
 
262
+ ```python
263
+ # Don't do this
264
+ history = self.all_messages # Entire conversation since session start
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  ```
266
 
267
+ **Fix:** Smart truncation (last N messages) or summarization.
268
 
269
+ ### Mistake 3: Mixing Instructions with Data
270
 
271
+ ```python
272
+ # Don't do this
273
+ prompt = f"You're a helpful assistant. Here's data: {data}. User asks: {query}"
274
  ```
 
 
275
 
276
+ **Fix:** Separate system instructions, data, and query into distinct layers.
 
277
 
278
+ ### Mistake 4: Static Context
279
 
280
+ ```python
281
+ # Don't do this
282
+ self.context = load_all_context() # Loaded once, used forever
283
  ```
 
 
 
 
 
 
 
 
 
284
 
285
+ **Fix:** Assemble context dynamically per query.
 
 
 
 
 
 
 
 
 
286
 
287
+ ### Mistake 5: Ignoring Token Costs
288
 
289
+ ```python
290
+ # Don't do this
291
+ # (No awareness of context size or cost)
 
292
  ```
293
 
294
+ **Fix:** Track token counts per layer. Visualize distribution. Optimize.
295
 
296
+ ## Code Architecture
 
 
 
297
 
298
+ ### The Agent
299
 
300
+ The main agent assembles context layer by layer:
 
 
301
 
302
  ```python
303
  class ContextEngineeringAgent:
304
+ def process_query(self, user_query: str):
305
+ # Layer 1: System instructions (stable)
306
+ # Layer 2: Conversation history (recent only)
307
+ history_text = self.memory.get_history_text()
308
+
309
+ # Layer 3: Retrieved knowledge (top-2 relevant)
310
+ retrieved_docs = self.knowledge_base.retrieve_relevant(user_query)
311
+
312
+ # Layer 4: User query
313
+ # Layer 5: Tools (automatically handled by agent)
314
+
315
+ # Assemble with clear structure
316
+ context_message = f"""Context from Knowledge Base:
317
+ {retrieved_docs}
 
 
 
 
 
318
 
319
  Previous Conversation:
320
  {history_text}
321
 
322
  Current Question:
323
  {user_query}"""
324
+
325
+ return self.agent.invoke({"messages": [{"role": "user", "content": context_message}]})
 
 
326
  ```
327
 
328
+ ### The RAG Component (Relevance in Action)
329
 
330
+ ```python
331
+ class KnowledgeBase:
332
+ def __init__(self):
333
+ # 8 documents total, but only retrieve top 2
334
+ self.documents = [
335
+ "AOV = total revenue / number of orders",
336
+ "Net Revenue = gross revenue - refunds - discounts",
337
+ # ... more documents
338
+ ]
339
+
340
+ # Retriever with k=2 (only top 2 docs)
341
+ self.retriever = self.vectorstore.as_retriever(search_kwargs={"k": 2})
342
+ ```
343
 
344
+ We have 8 documents, but only send the **top 2 most relevant** to the model. This is context engineering in action.
345
 
346
+ ### The Memory Component (Smart Truncation)
 
 
 
 
347
 
348
+ ```python
349
+ class ConversationMemory:
350
+ def __init__(self, max_messages: int = 4):
351
+ self.messages = []
352
+ self.max_messages = max_messages
353
+
354
+ def _truncate(self):
355
+ if len(self.messages) > self.max_messages:
356
+ self.messages = self.messages[-self.max_messages:]
357
+ ```
358
 
359
+ We limit history to 4 messages. For longer conversations, this prevents context overflow while maintaining relevant continuity.
360
 
361
+ **Note:** There are several approaches to handle conversation history when it becomes too long:
 
 
 
 
 
362
 
363
+ - **Trimming**: Keep only the most recent N messages (used here)
364
+ - **Summarization**: Compress older messages into summaries
365
+ - **Deletion**: Permanently remove certain states
366
+ - More info: [LangChain Memory Documentation](https://docs.langchain.com/oss/python/concepts/memory)
367
 
368
+ ## Configuration
 
 
369
 
370
+ Edit `config/settings.py` to customize:
371
 
372
+ ```python
373
+ class Settings:
374
+ # Model settings
375
+ MODEL_NAME = "gpt-4.1-mini"
376
+ TEMPERATURE = 0
377
+
378
+ # Memory settings
379
+ MAX_CONVERSATION_MESSAGES = 4
380
+
381
+ # RAG settings
382
+ RAG_TOP_K = 2
383
+
384
+ # UI settings
385
+ GRADIO_SERVER_PORT = 7860
386
+ ```
387
 
388
+ ## How to Practice Context Engineering
389
 
390
+ ### 1. Inspect Your Token Usage
 
 
391
 
392
+ ```python
393
+ def count_tokens(text: str) -> int:
394
+ # Simple estimate: ~4 chars per token
395
+ return len(text) // 4
396
+
397
+ print(f"Context size: {count_tokens(context)} tokens")
398
+ ```
399
 
400
+ ### 2. Separate Concerns
401
 
402
+ ```python
403
+ # Instead of one blob, create layers
404
+ context = {
405
+ "system": system_instructions,
406
+ "history": recent_messages,
407
+ "knowledge": retrieved_docs,
408
+ "query": user_question
409
+ }
410
+ ```
411
 
412
+ ### 3. Experiment with Context Size
 
413
 
414
+ ```python
415
+ # Try different values
416
+ retriever = vectorstore.as_retriever(search_kwargs={"k": k})
417
+ # Test k=1, k=2, k=5, k=10
418
+ # Measure: quality vs. cost vs. latency
419
+ ```
420
 
421
+ ### 4. Treat Context as First-Class
422
 
423
+ Don't think of context as "everything I stuff into the prompt." Think of it as a carefully engineered data pipeline with:
 
 
424
 
425
+ - **Sources** (RAG, memory, tools)
426
+ - **Filters** (relevance, recency, size)
427
+ - **Transformations** (formatting, structuring)
428
+ - **Quality checks** (token budgets, validation)
429
 
430
+ ## Key Takeaways
431
 
432
+ 1. **Context is multi-layered**: It's not just your prompt
433
+ 2. **Less is often more**: Relevant beats comprehensive
434
+ 3. **Structure matters**: Organization helps models reason
435
+ 4. **Dynamic beats static**: Assemble context per-query
436
+ 5. **Tokens cost money**: Engineering context saves budget
437
 
438
+ ## Why This Matters
439
 
440
+ As AI systems mature, **context design is becoming the main differentiator**:
 
 
 
 
441
 
442
+ 1. **Larger context windows ≠ free intelligence**: A 1M token context window doesn't mean you should use it all
443
+ 2. **AI agents depend on state & memory**: Poor context management = inconsistent behavior
444
+ 3. **Cost optimization is critical**: Every token costs money
445
+ 4. **Reliability > raw capability**: A GPT-3.5 with good context beats GPT-4 with bad context
446
 
447
+ ## Technologies
448
 
449
+ - **LangChain**: Agent framework and tools
450
+ - **OpenAI**: Language model (GPT-4.1-mini)
451
+ - **FAISS**: Vector store for RAG
452
+ - **Gradio**: Web interface
453
+ - **Python 3.11+**
454
 
455
  ## Contributing
456
 
457
+ This is an educational project designed to help developers understand context engineering. Feel free to:
458
+
459
+ - Open issues for bugs or suggestions
460
+ - Submit pull requests for improvements
461
+ - Use this as a learning resource for your own projects