A production-ready AI-powered code generation system that enforces deterministic code reuse through AST analysis, vector similarity search, and structural verification. Prevents code duplication by ensuring AI agents leverage existing utilities instead of creating redundant implementations.
Built during a 48-hour IBM Watsonx Challenge hackathon.
Dual-phase verification (namespace checking + structural similarity) with rolling subtask context management ensures generated code reuses existing functions instead of duplicating logic.
- π Semantic Code Search: ChromaDB + Jina embeddings for finding similar functions
- π Code Reuse Enforcement: Minimum 40% reuse score validation
- π« Plagiarism Detection: AST-based structural similarity checking (85% threshold)
- π Dependency Tracking: Import/call graph analysis with breaking change detection
- π€ Intelligent Task Decomposition: LLM-powered subtask breakdown (2-5 subtasks)
- π‘ Explanatory Feedback: Detailed failure explanations guide regeneration
- π Automatic Retry: Up to 3 retries with explanations
- π Dual Modes: Legacy (enforces reuse) vs Greenfield (no validation)
Repository β Indexing β Vector DB + Dependency Graph
β
User Request β Task Decomposition β Subtasks
β
For each subtask:
Global Context + Local Context (similar functions)
β
LLM Code Generation (Qwen)
β
Metric Validation (Legacy Mode)
β
Update Subtask Memory β Next Subtask
β
Final Code β Dependency Validation β Output
- Python 3.10+
- Node.js 18+ (for frontend)
- Hugging Face API Token
# Clone repository
git clone <your-repo-url>
cd context-aware-agent
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Setup environment
cp .env.example .env
# Edit .env and add your HUGGINGFACE_API_TOKENcd frontend
npm install
npm run dev# Using CLI
python cli.py index ./path/to/your/repo
# Using API
curl -X POST "http://localhost:8000/index/repository" \
-H "Content-Type: application/json" \
-d '{"repository_path": "./path/to/repo"}'# Using CLI
python cli.py generate \
"Add email validation to user registration" \
--target-file src/services/user_service.py \
--mode legacy \
--output generated_code.py
# Using API
curl -X POST "http://localhost:8000/generate" \
-H "Content-Type: application/json" \
-d '{
"user_request": "Add email validation",
"target_file": "src/services/user_service.py",
"mode": "legacy"
}'# Using CLI
python cli.py search "email validation" --top-k 5
# Using API
curl "http://localhost:8000/search/functions?query=email+validation&top_k=5"# Development
python -m src.api.main
# Production
uvicorn src.api.main:app --host 0.0.0.0 --port 8000POST /index/repository- Index a repositoryPOST /generate- Generate codeGET /search/functions- Search for similar functionsGET /stats- Get indexing statisticsGET /config- Get current configurationWS /ws- WebSocket for real-time updates
// Connect
const ws = new WebSocket('ws://localhost:8000/ws');
// Subscribe to events
ws.send(JSON.stringify({ type: 'subscribe' }));
// Receive events
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
// data.type: indexing_started, indexing_completed, generation_started, etc.
};reuse_score = |called_functions β© repo_functions| / |called_functions|
- Threshold: 40% minimum
- Purpose: Ensure code calls existing functions
jaccard_similarity = |tokens1 β© tokens2| / |tokens1 βͺ tokens2|
- Threshold: 85% maximum
- Purpose: Detect code plagiarism (copying logic instead of calling)
- Checks for breaking changes in dependent files
- Validates signature compatibility
- Reports import resolution issues
Edit config.yaml to customize:
agent:
mode: "legacy" # or "greenfield"
llm:
model: "Qwen/Qwen2.5-Coder-32B-Instruct"
temperature: 0.2
metrics:
namespace:
min_reuse_score: 0.4
structural:
max_similarity: 0.85
retry:
max_retries: 3
context:
local:
min_similarity: 0.7
max_k: 5context-aware-agent/
βββ src/
β βββ indexing/ # AST parsing, vector DB, dependency graphs
β βββ agent/ # Task decomposition, context building, orchestration
β βββ metrics/ # Validation (namespace, structural, dependency)
β βββ models/ # Pydantic data models
β βββ utils/ # Config, logging
β βββ api/ # FastAPI server
βββ frontend/ # React frontend (optional)
βββ tests/ # Unit and integration tests
βββ cli.py # Command-line interface
βββ config.yaml # Configuration
βββ requirements.txt # Python dependencies
# Run all tests
pytest
# Run with coverage
pytest --cov=src --cov-report=html
# Run specific test
pytest tests/unit/test_ast_parser.pyThe frontend provides:
- Repository Upload: Drag-and-drop or file browser
- Real-time Indexing: Progress bar with file count
- Code Generation Interface: Text input with mode selection
- Split View: Generated code | Similar functions found
- Metrics Dashboard: Reuse scores, similarity graphs, violations
- WebSocket Updates: Live progress notifications
cd frontend
npm install
npm run dev # Development server
npm run build # Production build- Small repo (10 files): ~5 seconds
- Medium repo (50 files): ~30 seconds
- Large repo (500 files): ~5 minutes
- Vector search: <100ms
- Dependency traversal: <50ms
- Full validation: <500ms
-
"HUGGINGFACE_API_TOKEN not set"
- Copy
.env.exampleto.env - Add your Hugging Face API token
- Copy
-
"Repository not indexed"
- Run
python cli.py index ./path/to/repofirst
- Run
-
Import errors
- Ensure virtual environment is activated
- Run
pip install -r requirements.txt
-
ChromaDB errors
- Delete
./chroma_dbdirectory - Re-index repository
- Delete
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open Pull Request
MIT License - see LICENSE file for details
- ChromaDB for vector database
- Jina AI for code embeddings
- Qwen (Alibaba) for LLM capabilities
- FastAPI for API framework
For questions or support, please open an issue on GitHub.