Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
89 commits
Select commit Hold shift + click to select a range
0d58062
Add context engineering course with Redis University Class Agent
abrookins Sep 25, 2025
2064e61
Temporarily ignore context engineering notebooks in CI
abrookins Sep 25, 2025
6be84e5
Fix notebooks to work in CI environments
abrookins Sep 26, 2025
73c9161
Fix final import issue in 03_project_overview notebook
abrookins Sep 26, 2025
065e91a
Fix real issues: Install package in CI and use real classes
abrookins Sep 26, 2025
2f014d5
Fix RedisVL API compatibility issue in memory retrieval
abrookins Sep 26, 2025
3011f52
Fix RedisVL API format change - handle both dict and object results
abrookins Sep 26, 2025
7b5059f
Clean up notebook 01: Remove installation guards and update memory te…
abrookins Sep 29, 2025
8f53551
Implement working memory with long-term extraction strategy awareness
abrookins Sep 29, 2025
4c80a28
Complete Context Engineering course with all 15 notebooks and referen…
abrookins Sep 30, 2025
8cb9c10
Temporarily ignore context engineering notebooks in CI
abrookins Sep 30, 2025
8722b48
Revert: Remove context engineering notebooks from ignore list
abrookins Sep 30, 2025
e7ce2ba
Fix notebook imports: MemoryManager -> MemoryClient
abrookins Sep 30, 2025
db78b54
Add agent-memory-client to dependencies
abrookins Sep 30, 2025
8abb21d
Fix working memory notebook to use actual MemoryClient API
abrookins Sep 30, 2025
3f7ed02
Fix notebook cell dependencies for independent execution
abrookins Sep 30, 2025
65ae681
Fix MemoryAPIClient initialization to use MemoryClientConfig
abrookins Sep 30, 2025
6804da9
Fix method name: set_working_memory -> put_working_memory
abrookins Sep 30, 2025
a07e72c
Comment out memory_manager calls in notebooks
abrookins Sep 30, 2025
b68536e
Convert memory_manager cells to markdown in 02_role_of_context_engine
abrookins Sep 30, 2025
64ee02c
Fix memory_type -> memory_types parameter in notebooks
abrookins Sep 30, 2025
cff357a
Fix count_tokens function dependencies in context window notebook
abrookins Sep 30, 2025
19e671f
Fix put_working_memory() call signature
abrookins Sep 30, 2025
0e71885
Fix MemoryRecord creation to include required id field
abrookins Sep 30, 2025
7efbe57
Add Docker Compose setup for Agent Memory Server
abrookins Sep 30, 2025
20ec0d1
Fix Agent Memory Server Docker image path
abrookins Sep 30, 2025
e3111a8
Fix MemoryRecord creation in save_working_memory
abrookins Oct 1, 2025
8ff0982
Add get_or_create_working_memory and update notebooks
abrookins Oct 1, 2025
80a71f6
Improve OpenAI API key handling and CI debugging
abrookins Oct 1, 2025
0fbbc06
Make Agent Memory Server startup more lenient in CI
abrookins Oct 1, 2025
5cd45eb
Fix LOG_LEVEL environment variable for Agent Memory Server
abrookins Oct 1, 2025
b1a051c
Fix get_or_create_working_memory to unpack tuple return value
abrookins Oct 1, 2025
71f93c0
Fix create_memory to handle tuple return from create_long_term_memories
abrookins Oct 1, 2025
ad8de72
Remove memory_client wrapper and use MemoryAPIClient directly
abrookins Oct 1, 2025
0482676
Fix agent.py to use actual MemoryAPIClient API
abrookins Oct 1, 2025
93a3559
Fix tools.py to use actual MemoryAPIClient API
abrookins Oct 1, 2025
4e1c4c2
Update notebooks to use MemoryAPIClient directly (partial)
abrookins Oct 1, 2025
39290e6
Add comprehensive memory client migration documentation
abrookins Oct 1, 2025
ff2c4ac
Fix all save_working_memory calls to use put_working_memory
abrookins Oct 1, 2025
bd66460
Fix remaining import issues in notebooks
abrookins Oct 1, 2025
07ac032
Fix section-3-memory/02_long_term_memory.ipynb API calls
abrookins Oct 1, 2025
0f19481
Fix remaining API issues in section-3-memory notebooks
abrookins Oct 1, 2025
30ea09e
Fix ClientMemoryRecord import - use agent_memory_client.models
abrookins Oct 1, 2025
01b693a
Fix remaining query= to text= in 02_long_term_memory.ipynb
abrookins Oct 1, 2025
7780258
Fix memory_type parameter to use MemoryType filter object
abrookins Oct 1, 2025
d6b36b0
Fix ClientMemoryRecord memory_type - use string not MemoryType filter
abrookins Oct 1, 2025
6f67685
Fix ALL remaining query= to text= in notebooks
abrookins Oct 1, 2025
61a6c3a
Fix missing MemoryClientConfig import in 01_working_memory notebook
abrookins Oct 1, 2025
da51403
Add missing user_id parameter to get_or_create_working_memory calls
abrookins Oct 1, 2025
2675d88
Fix missing comma in get_or_create_working_memory call
abrookins Oct 1, 2025
85cbe9e
Fix user_id consistency in 01_working_memory notebook
abrookins Oct 1, 2025
015c4e3
Fix syntax errors and API usage in section-3 notebooks
abrookins Oct 1, 2025
e5f5b79
Fix tool invocation in 04_memory_tools notebook
abrookins Oct 1, 2025
55e19d2
Fix list comprehension in 03_memory_integration notebook
abrookins Oct 1, 2025
8da9cc7
Add missing user_id to all get_or_create_working_memory calls in 03_m…
abrookins Oct 1, 2025
288f858
Fix all API usage issues in 03_memory_integration notebook
abrookins Oct 1, 2025
5c77fd9
Fix get_or_create_working_memory issue in 03_memory_integration
abrookins Oct 1, 2025
bc37b82
Upgrade agent-memory-client to 0.12.3
abrookins Oct 1, 2025
1677e59
Fix redisvl API compatibility in course_manager
abrookins Oct 1, 2025
1ee634b
Add get_all_courses method to CourseManager
abrookins Oct 1, 2025
45353bf
Add missing MemoryClientConfig import to section-4 notebooks
abrookins Oct 1, 2025
46bf6bc
Fix remaining issues in section-4 notebooks
abrookins Oct 1, 2025
1168b32
Fix final issues in section-4 notebooks
abrookins Oct 1, 2025
a92fe1e
Fix Redis get() calls in 05_crafting_data_for_llms
abrookins Oct 1, 2025
2092f1c
Fix KeyError in 05_crafting_data_for_llms
abrookins Oct 1, 2025
0a81a94
Fix len(memories) in 05_crafting_data_for_llms
abrookins Oct 1, 2025
9aae1c1
Fix memories slicing in 05_crafting_data_for_llms
abrookins Oct 1, 2025
f91263b
Update Redis version to 8.2 in GitHub Actions workflows
abrookins Oct 1, 2025
e113888
Remove OpenAI API key check and logging from workflow
abrookins Oct 1, 2025
3cc032a
Use redis:8.2 image in test.yml workflow
abrookins Oct 1, 2025
b3bec17
Add search_courses_tool to demonstrate catalog view + RAG pattern
abrookins Oct 1, 2025
a0680f1
Change to get_course_details tool that retrieves by course code
abrookins Oct 1, 2025
ffc8389
Add detailed explanation of data integration challenges
abrookins Oct 1, 2025
fe4149f
Fix JSON syntax error in 05_crafting_data_for_llms.ipynb
abrookins Oct 1, 2025
a0cf9a0
Clarify LLM control statement in automatic extraction section
abrookins Oct 1, 2025
53fb3ef
Clarify that it's the application's LLM that has control in tool-base…
abrookins Oct 1, 2025
0de2ddb
Add performance tradeoffs to memory extraction comparison
abrookins Oct 1, 2025
7637eff
Update 04_memory_tools to use built-in memory client tool schemas
abrookins Oct 1, 2025
c4c7501
Keep LangChain/LangGraph pattern while using memory client tools
abrookins Oct 1, 2025
036ff05
Use memory client's built-in LangChain/LangGraph integration
abrookins Oct 2, 2025
af26356
Update reference agent to use memory client's LangChain integration
abrookins Oct 2, 2025
6bc85d4
Add schema printing to memory tools notebook for debugging
abrookins Oct 2, 2025
5396372
Add schema printing to memory tools notebook
abrookins Oct 2, 2025
22ceafa
Catch and return tool validation errors to LLM
abrookins Oct 2, 2025
8c10741
Fix create_memory_tools call in working memory notebook
abrookins Oct 2, 2025
bab8f38
Simplify setup and clean up notebooks
abrookins Oct 3, 2025
07c1e91
Bump agent-memory-client to 0.12.6
abrookins Oct 3, 2025
a9b8a7a
Reorganize notebook setup and update agent-memory-server to 0.12.3
abrookins Oct 5, 2025
96a1e2a
Fix notebook failures: remove non-existent memory_index_name and meta…
abrookins Oct 5, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 51 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,14 @@ jobs:

services:
redis:
image: redis:8.0-M03
image: redis:8.2
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 5

steps:
- uses: actions/checkout@v3
Expand All @@ -99,18 +104,63 @@ jobs:
with:
python-version: ${{ env.PYTHON_VERSION }}

# Start Agent Memory Server
- name: Start Agent Memory Server
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
# Start the Agent Memory Server
docker run -d \
--name agent-memory-server \
--network host \
-e REDIS_URL=redis://localhost:6379 \
-e OPENAI_API_KEY=$OPENAI_API_KEY \
-e LOG_LEVEL=INFO \
ghcr.io/redis/agent-memory-server:latest

# Wait for memory server to be ready
echo "Waiting for Agent Memory Server to be ready..."
for i in {1..30}; do
if curl -f http://localhost:8000/health 2>/dev/null; then
echo "✅ Agent Memory Server is ready!"
break
fi
echo "Waiting... ($i/30)"
sleep 2
done

# Show status but don't fail if server isn't ready
if curl -f http://localhost:8000/health 2>/dev/null; then
echo "✅ Agent Memory Server is healthy"
else
echo "⚠️ WARNING: Agent Memory Server may not be ready"
echo "Docker logs:"
docker logs agent-memory-server || true
fi

- name: Create and activate venv
run: |
python -m venv venv
source venv/bin/activate
pip install --upgrade pip setuptools wheel
pip install pytest nbval

# Install the redis-context-course package and its dependencies
cd python-recipes/context-engineering/reference-agent
pip install -e .

- name: Test notebook
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
COHERE_API_KEY: ${{ secrets.COHERE_API_KEY }}
AGENT_MEMORY_URL: http://localhost:8000
REDIS_URL: redis://localhost:6379
run: |
echo "Testing notebook: ${{ matrix.notebook }}"
source venv/bin/activate
pytest --nbval-lax --disable-warnings "${{ matrix.notebook }}"

- name: Show Agent Memory Server logs on failure
if: failure()
run: |
docker logs agent-memory-server
2 changes: 2 additions & 0 deletions python-recipes/context-engineering/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# OpenAI API Key (required to pass to the API container)
OPENAI_API_KEY=your-openai-api-key-here
2 changes: 2 additions & 0 deletions python-recipes/context-engineering/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
venv
.env
286 changes: 286 additions & 0 deletions python-recipes/context-engineering/COURSE_SUMMARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,286 @@
# Context Engineering Course - Complete Summary

## Overview

This course teaches production-ready context engineering for AI agents using Redis and the Agent Memory Server. It covers everything from fundamentals to advanced optimization techniques.

## Course Structure

### Section 1: Introduction (3 notebooks)
1. **What is Context Engineering?** - Core concepts and importance
2. **Setting Up Your Environment** - Installation and configuration
3. **Project Overview** - Understanding the reference agent

### Section 2: System Context (3 notebooks)
1. **System Instructions** - Crafting effective system prompts
2. **Defining Tools** - Giving agents capabilities
3. **Tool Selection Strategies** (Advanced) - Improving tool choice

**Key Patterns:**
- Progressive system prompt building
- Tool schema design with examples
- Clear naming conventions
- Detailed descriptions with when/when-not guidance

### Section 3: Memory (4 notebooks)
1. **Working Memory with Extraction Strategies** - Session-scoped context
2. **Long-term Memory** - Cross-session knowledge
3. **Memory Integration** - Combining working and long-term memory
4. **Memory Tools** (Advanced) - LLM control over memory

**Key Patterns:**
- Automatic memory extraction
- Semantic search for retrieval
- Memory type selection (semantic vs episodic)
- Tool-based memory management

### Section 4: Optimizations (5 notebooks)
1. **Context Window Management** - Handling token limits
2. **Retrieval Strategies** - RAG, summaries, and hybrid approaches
3. **Grounding with Memory** - Using memory to resolve references
4. **Tool Optimization** (Advanced) - Selective tool exposure
5. **Crafting Data for LLMs** (Advanced) - Creating structured views

**Key Patterns:**
- Token budget estimation
- Hybrid retrieval (summary + RAG)
- Tool filtering by intent
- Retrieve → Summarize → Stitch → Save pattern
- Structured view creation

## Reference Agent Components

### Core Modules

**`course_manager.py`**
- Course catalog management
- Vector search for courses
- Course data models

**`memory_client.py`**
- Working memory operations
- Long-term memory operations
- Integration with Agent Memory Server

**`agent.py`**
- Main agent implementation
- LangGraph workflow
- State management

### New Modules (From Course Content)

**`tools.py`** (Section 2)
- `create_course_tools()` - Search, get details, check prerequisites
- `create_memory_tools()` - Store and search memories
- `select_tools_by_keywords()` - Simple tool filtering

**`optimization_helpers.py`** (Section 4)
- `count_tokens()` - Token counting for any model
- `estimate_token_budget()` - Budget breakdown
- `hybrid_retrieval()` - Combine summary + search
- `create_summary_view()` - Structured summaries
- `create_user_profile_view()` - User profile generation
- `filter_tools_by_intent()` - Keyword-based filtering
- `classify_intent_with_llm()` - LLM-based classification
- `extract_references()` - Find grounding needs
- `format_context_for_llm()` - Combine context sources

### Examples

**`examples/advanced_agent_example.py`**
- Complete agent using all patterns
- Tool filtering enabled
- Token budget tracking
- Memory integration
- Production-ready structure

## Key Concepts by Section

### Section 2: System Context
- **System vs Retrieved Context**: Static instructions vs dynamic data
- **Tool Schemas**: Name, description, parameters
- **Tool Selection**: How LLMs choose tools
- **Best Practices**: Clear names, detailed descriptions, examples

### Section 3: Memory
- **Working Memory**: Session-scoped, conversation history
- **Long-term Memory**: User-scoped, persistent facts
- **Memory Types**: Semantic (facts), Episodic (events), Message (conversations)
- **Automatic Extraction**: Agent Memory Server extracts important facts
- **Memory Flow**: Load → Search → Process → Save → Extract

### Section 4: Optimizations
- **Token Budgets**: Allocating context window space
- **Retrieval Strategies**: Full context (bad), RAG (good), Summaries (compact), Hybrid (best)
- **Grounding**: Resolving references (pronouns, descriptions, implicit)
- **Tool Filtering**: Show only relevant tools based on intent
- **Structured Views**: Pre-computed summaries for LLM consumption

## Production Patterns

### 1. Complete Memory Flow
```python
# Load working memory
working_memory = await memory_client.get_working_memory(session_id, model_name)

# Search long-term memory
memories = await memory_client.search_memories(query, limit=5)

# Build context
system_prompt = build_prompt(instructions, memories)

# Process with LLM
response = llm.invoke(messages)

# Save working memory (triggers extraction)
await memory_client.save_working_memory(session_id, messages)
```

### 2. Hybrid Retrieval
```python
# Pre-computed summary
summary = load_catalog_summary()

# Targeted search
specific_items = await search_courses(query, limit=3)

# Combine
context = f"{summary}\n\nRelevant items:\n{specific_items}"
```

### 3. Tool Filtering
```python
# Filter tools by intent
relevant_tools = filter_tools_by_intent(query, tool_groups)

# Bind only relevant tools
llm_with_tools = llm.bind_tools(relevant_tools)
```

### 4. Token Budget Management
```python
# Estimate budget
budget = estimate_token_budget(
system_prompt=prompt,
working_memory_messages=10,
long_term_memories=5,
retrieved_context_items=3
)

# Check if within limits
if budget['total_with_response'] > 128000:
# Trigger summarization or reduce context
```

### 5. Structured Views
```python
# Retrieve data
items = await get_all_items()

# Summarize
summary = await create_summary_view(items, group_by="category")

# Save for reuse
redis_client.set("summary_view", summary)

# Use in prompts
system_prompt = f"Overview:\n{summary}\n\nInstructions:..."
```

## Usage in Notebooks

All patterns are demonstrated in notebooks with:
- ✅ Conceptual explanations
- ✅ Bad examples (what not to do)
- ✅ Good examples (best practices)
- ✅ Runnable code
- ✅ Testing and verification
- ✅ Exercises for practice

## Importing in Your Code

```python
from redis_context_course import (
# Core
CourseManager,
MemoryClient,

# Tools (Section 2)
create_course_tools,
create_memory_tools,
select_tools_by_keywords,

# Optimizations (Section 4)
count_tokens,
estimate_token_budget,
hybrid_retrieval,
create_summary_view,
create_user_profile_view,
filter_tools_by_intent,
classify_intent_with_llm,
extract_references,
format_context_for_llm,
)
```

## Learning Path

1. **Start with Section 1** - Understand fundamentals
2. **Work through Section 2** - Build system context and tools
3. **Master Section 3** - Implement memory management
4. **Optimize with Section 4** - Apply production patterns
5. **Study advanced_agent_example.py** - See it all together
6. **Build your own agent** - Apply to your use case

## Key Takeaways

### What Makes a Production-Ready Agent?

1. **Clear System Instructions** - Tell the agent what to do
2. **Well-Designed Tools** - Give it capabilities with clear descriptions
3. **Memory Integration** - Remember context across sessions
4. **Token Management** - Stay within limits efficiently
5. **Smart Retrieval** - Hybrid approach (summary + RAG)
6. **Tool Filtering** - Show only relevant tools
7. **Structured Views** - Pre-compute summaries for efficiency

### Common Pitfalls to Avoid

❌ **Don't:**
- Include all tools on every request
- Use vague tool descriptions
- Ignore token budgets
- Use only full context or only RAG
- Forget to save working memory
- Store everything in long-term memory

✅ **Do:**
- Filter tools by intent
- Write detailed tool descriptions with examples
- Estimate and monitor token usage
- Use hybrid retrieval (summary + targeted search)
- Save working memory to trigger extraction
- Store only important facts in long-term memory

## Next Steps

After completing this course, you can:

1. **Extend the reference agent** - Add new tools and capabilities
2. **Apply to your domain** - Adapt patterns to your use case
3. **Optimize further** - Experiment with different strategies
4. **Share your learnings** - Contribute back to the community

## Resources

- **Agent Memory Server Docs**: [Link to docs]
- **Redis Documentation**: https://redis.io/docs
- **LangChain Documentation**: https://python.langchain.com
- **Course Repository**: [Link to repo]

---

**Course Version**: 1.0
**Last Updated**: 2024-09-30
**Total Notebooks**: 15 (3 intro + 3 system + 4 memory + 5 optimizations)

Loading