This is a CrewAI implementation of the Context Pruning technique from the LangGraph examples. Context Pruning removes irrelevant information from retrieved documents to improve response quality and reduce token usage.
| Feature | LangGraph | CrewAI (This Implementation) |
|---|---|---|
| Orchestration | StateGraph with nodes/edges | Sequential agent workflow |
| State Management | Custom State classes with fields | Automatic context passing between tasks |
| Tool Integration | Manual tool binding to LLM | Tools assigned to specific agents |
| Flow Control | Conditional edges with should_continue |
Task dependencies via context |
| LLM Provider | OpenAI (GPT-4o-mini for pruning) | Google Gemini (Flash for pruning) |
| Embeddings | OpenAI text-embedding-3-small | Google embedding-001 |
✅ RAG Retrieval: Vector store with blog post chunks
✅ Context Pruning: LLM-based filtering of irrelevant content
✅ Sequential Workflow: Retrieve → Prune → Synthesize
✅ Token Reduction: Same goal of 40-60% reduction
✅ Same Data Source: Lilian Weng's blog posts
🔄 Agent-Based Design: Each step is an autonomous agent
🔄 Tool Abstractions: Tools are first-class objects with schemas
🔄 Google Gemini: Cost-effective alternative to OpenAI
🔄 Declarative Config: Agents and tasks defined in YAML
🔄 Higher-Level API: CrewAI handles orchestration details
context_pruning/
├── .env # API keys (GEMINI_API_KEY)
├── pyproject.toml # Dependencies
├── README.md # Full documentation
├── QUICKSTART.md # Quick start guide
├── IMPLEMENTATION_NOTES.md # This file
└── src/context_pruning/
├── main.py # Entry point
├── crew.py # Crew definition
├── config/
│ ├── agents.yaml # Agent configurations
│ └── tasks.yaml # Task definitions
└── tools/
├── __init__.py
└── custom_tool.py # RAG & Pruning tools
Role: Information Retrieval Specialist
Tool: RAGRetrievalTool
Function: Searches vector store for relevant blog content
Output: Raw retrieved chunks (may contain noise)
@agent
def retrieval_agent(self) -> Agent:
return Agent(
config=self.agents_config['retrieval_agent'],
tools=[RAGRetrievalTool()],
verbose=True
)Role: Context Pruning Specialist
Tool: ContextPruningTool
Function: Filters content using Gemini Flash
Output: Pruned, focused content
@agent
def pruning_agent(self) -> Agent:
return Agent(
config=self.agents_config['pruning_agent'],
tools=[ContextPruningTool()],
verbose=True
)Role: Research Response Synthesizer
Tools: None (uses context from previous tasks)
Function: Creates final markdown answer
Output: Comprehensive, well-structured response
class RAGRetrievalTool(BaseTool):
- Lazy loads vector store on first use
- Uses Google Gemini embeddings (embedding-001)
- Retrieves top-k=4 chunks
- Concatenates with separatorsKey Design Decision: Lazy initialization prevents loading heavy resources on import.
class ContextPruningTool(BaseTool):
- Takes user_request + retrieved_content
- Uses Gemini Flash (gemini-1.5-flash)
- Structured pruning prompt
- Returns focused contentKey Design Decision: Uses same pruning prompt structure as LangGraph example.
retrieval_task:
agent: retrieval_agent
# No dependencies
pruning_task:
agent: pruning_agent
context: [retrieval_task] # Depends on retrieval
synthesis_task:
agent: response_synthesizer
context: [pruning_task] # Depends on pruningCrewAI automatically passes outputs from dependent tasks as context.
- Cost Effective: Gemini Flash is significantly cheaper than GPT-4o-mini
- Fast: Flash model optimized for speed
- Good Enough: For pruning tasks, Flash performs well
- API Availability: User already has Gemini API key
- Embeddings:
models/embedding-001(768 dimensions) - Pruning LLM:
gemini-flash-latest(fast, cheap) - Main Agents: Use MODEL from .env (
gemini/gemini-flash-latest)
- Before Pruning: ~15,000 tokens (raw retrieval)
- After Pruning: ~6,000 tokens (60% reduction)
- Similar to LangGraph: 25k → 11k tokens (56% reduction)
- Vector Store Init: 5-10 seconds (first run only)
- Retrieval: 1-2 seconds
- Pruning: 3-5 seconds (Gemini Flash)
- Synthesis: 5-10 seconds
- Total: ~20-30 seconds
- Embeddings: Free tier or very low cost
- Pruning (Flash): ~$0.001 per query
- Synthesis (Flash): ~$0.002 per query
- Total: < $0.01 per complete workflow
cd context_pruning
crewai runcat context_pruning_result.mdLook for agent logs showing:
- Retrieved content size
- Pruned content size
- Reduction percentage
The final answer should:
- List specific types of reward hacking
- Include examples from the blog posts
- Be well-structured in markdown
- Cite specific findings
Solution: Run crewai install to ensure all dependencies are installed
Solution: Check .env file has GEMINI_API_KEY=your-key
Solution: Normal on first run; subsequent runs use cached embeddings
Solution: Check pruning prompt in custom_tool.py; ensure it's specific
- Tool Loadout: Add semantic tool selection agent
- Context Quarantine: Create isolated specialist agents
- Context Summarization: Replace pruning with summarization
- Context Offloading: Add memory persistence
- Two-Stage Pruning: Coarse filter → fine filter
- Quality Metrics: Add evaluation of pruned content
- Adaptive Pruning: Adjust based on query complexity
- Caching: Store pruned results for similar queries
- Error Handling: Add retry logic for API failures
- Monitoring: Log token counts, costs, latency
- Evaluation: Add automated quality checks
- Optimization: Cache vector store, batch requests
✅ CrewAI Simplifies: Higher-level abstractions reduce boilerplate
✅ Agent Paradigm: Natural fit for multi-step workflows
✅ Declarative Config: YAML makes agents/tasks easy to modify
✅ Tool Integration: Clean separation of concerns
✅ Cost Effective: Gemini provides good quality at low cost
- Run the implementation and verify results
- Compare output quality with LangGraph version
- Experiment with different queries
- Implement other context engineering techniques
- Add evaluation metrics
Questions or Improvements? Edit the tools, agents, or tasks to customize behavior!