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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RAG retriever for spec generation.
|
| 2 |
+
|
| 3 |
+
Builds a vector store from training pairs (code -> spec) and retrieves
|
| 4 |
+
the most similar examples at inference time to provide few-shot context
|
| 5 |
+
to the student model. This improves quality by giving the small model
|
| 6 |
+
relevant examples of what good specs look like for similar code patterns.
|
| 7 |
+
|
| 8 |
+
Uses ChromaDB for local vector storage and sentence-transformers for
|
| 9 |
+
code embedding.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SpecRetriever:
|
| 19 |
+
"""Retrieves similar code/spec pairs for RAG-augmented generation."""
|
| 20 |
+
|
| 21 |
+
def __init__(
|
| 22 |
+
self,
|
| 23 |
+
collection_name: str = "codewraith_specs",
|
| 24 |
+
persist_dir: str = "data/chromadb",
|
| 25 |
+
embedding_model: str = "all-MiniLM-L6-v2",
|
| 26 |
+
):
|
| 27 |
+
"""Initialize the retriever.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
collection_name: ChromaDB collection name.
|
| 31 |
+
persist_dir: Directory to persist the vector store.
|
| 32 |
+
embedding_model: Sentence-transformers model for embeddings.
|
| 33 |
+
"""
|
| 34 |
+
self.collection_name = collection_name
|
| 35 |
+
self.persist_dir = persist_dir
|
| 36 |
+
self.embedding_model_name = embedding_model
|
| 37 |
+
self._client = None
|
| 38 |
+
self._collection = None
|
| 39 |
+
self._embedding_fn = None
|
| 40 |
+
|
| 41 |
+
def _get_client(self):
|
| 42 |
+
"""Lazy-load ChromaDB client."""
|
| 43 |
+
if self._client is None:
|
| 44 |
+
import chromadb
|
| 45 |
+
|
| 46 |
+
self._client = chromadb.PersistentClient(path=self.persist_dir)
|
| 47 |
+
return self._client
|
| 48 |
+
|
| 49 |
+
def _get_embedding_fn(self):
|
| 50 |
+
"""Lazy-load embedding function."""
|
| 51 |
+
if self._embedding_fn is None:
|
| 52 |
+
from chromadb.utils import embedding_functions
|
| 53 |
+
|
| 54 |
+
self._embedding_fn = embedding_functions.SentenceTransformerEmbeddingFunction(
|
| 55 |
+
model_name=self.embedding_model_name
|
| 56 |
+
)
|
| 57 |
+
return self._embedding_fn
|
| 58 |
+
|
| 59 |
+
def _get_collection(self):
|
| 60 |
+
"""Get or create the ChromaDB collection."""
|
| 61 |
+
if self._collection is None:
|
| 62 |
+
client = self._get_client()
|
| 63 |
+
self._collection = client.get_or_create_collection(
|
| 64 |
+
name=self.collection_name,
|
| 65 |
+
embedding_function=self._get_embedding_fn(),
|
| 66 |
+
)
|
| 67 |
+
return self._collection
|
| 68 |
+
|
| 69 |
+
def build_index(
|
| 70 |
+
self,
|
| 71 |
+
dataset_path: str = "data/training_pairs_clean.jsonl",
|
| 72 |
+
batch_size: int = 50,
|
| 73 |
+
) -> int:
|
| 74 |
+
"""Build the vector index from training pairs.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
dataset_path: Path to the cleaned JSONL training data.
|
| 78 |
+
batch_size: Number of pairs to add per batch.
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
Number of pairs indexed.
|
| 82 |
+
"""
|
| 83 |
+
collection = self._get_collection()
|
| 84 |
+
|
| 85 |
+
# Check if already populated
|
| 86 |
+
existing = collection.count()
|
| 87 |
+
if existing > 0:
|
| 88 |
+
print(f"Collection already has {existing} entries. Skipping rebuild.")
|
| 89 |
+
print("Delete data/chromadb/ to rebuild from scratch.")
|
| 90 |
+
return existing
|
| 91 |
+
|
| 92 |
+
pairs = []
|
| 93 |
+
with Path(dataset_path).open(encoding="utf-8") as f:
|
| 94 |
+
for line in f:
|
| 95 |
+
if line.strip():
|
| 96 |
+
pairs.append(json.loads(line))
|
| 97 |
+
|
| 98 |
+
print(f"Indexing {len(pairs)} training pairs...")
|
| 99 |
+
|
| 100 |
+
for i in range(0, len(pairs), batch_size):
|
| 101 |
+
batch = pairs[i : i + batch_size]
|
| 102 |
+
|
| 103 |
+
ids = [f"pair_{i + j}" for j in range(len(batch))]
|
| 104 |
+
documents = [p["input"] for p in batch]
|
| 105 |
+
metadatas = [
|
| 106 |
+
{
|
| 107 |
+
"spec": p["output"],
|
| 108 |
+
"source_file": p.get("source_file", "unknown"),
|
| 109 |
+
}
|
| 110 |
+
for p in batch
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
collection.add(ids=ids, documents=documents, metadatas=metadatas)
|
| 114 |
+
print(f" Indexed {min(i + batch_size, len(pairs))}/{len(pairs)}")
|
| 115 |
+
|
| 116 |
+
total = collection.count()
|
| 117 |
+
print(f"Done. {total} pairs indexed in {self.persist_dir}")
|
| 118 |
+
return total
|
| 119 |
+
|
| 120 |
+
def retrieve(
|
| 121 |
+
self,
|
| 122 |
+
source_code: str,
|
| 123 |
+
n_results: int = 3,
|
| 124 |
+
) -> list[dict[str, str]]:
|
| 125 |
+
"""Retrieve the most similar code/spec pairs.
|
| 126 |
+
|
| 127 |
+
Args:
|
| 128 |
+
source_code: Input Python source code to find matches for.
|
| 129 |
+
n_results: Number of similar examples to retrieve.
|
| 130 |
+
|
| 131 |
+
Returns:
|
| 132 |
+
List of dicts with 'code' and 'spec' keys, ordered by similarity.
|
| 133 |
+
"""
|
| 134 |
+
collection = self._get_collection()
|
| 135 |
+
|
| 136 |
+
if collection.count() == 0:
|
| 137 |
+
return []
|
| 138 |
+
|
| 139 |
+
results = collection.query(
|
| 140 |
+
query_texts=[source_code],
|
| 141 |
+
n_results=min(n_results, collection.count()),
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
examples = []
|
| 145 |
+
for doc, meta in zip(
|
| 146 |
+
results["documents"][0],
|
| 147 |
+
results["metadatas"][0],
|
| 148 |
+
):
|
| 149 |
+
examples.append(
|
| 150 |
+
{
|
| 151 |
+
"code": doc,
|
| 152 |
+
"spec": meta["spec"],
|
| 153 |
+
"source_file": meta.get("source_file", "unknown"),
|
| 154 |
+
}
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
return examples
|
| 158 |
+
|
| 159 |
+
def format_context(
|
| 160 |
+
self,
|
| 161 |
+
examples: list[dict[str, str]],
|
| 162 |
+
max_chars: int = 6000,
|
| 163 |
+
) -> str:
|
| 164 |
+
"""Format retrieved examples as context for the model.
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
examples: Retrieved code/spec pairs.
|
| 168 |
+
max_chars: Maximum total characters to include.
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
Formatted string of examples to prepend to the prompt.
|
| 172 |
+
"""
|
| 173 |
+
if not examples:
|
| 174 |
+
return ""
|
| 175 |
+
|
| 176 |
+
parts = ["Here are examples of Python code and their specifications:\n"]
|
| 177 |
+
total = len(parts[0])
|
| 178 |
+
|
| 179 |
+
for i, ex in enumerate(examples, 1):
|
| 180 |
+
code_preview = ex["code"][:1500]
|
| 181 |
+
spec_preview = ex["spec"][:1500]
|
| 182 |
+
|
| 183 |
+
block = (
|
| 184 |
+
f"\n--- Example {i} ---\n"
|
| 185 |
+
f"Code:\n```python\n{code_preview}\n```\n"
|
| 186 |
+
f"Specification:\n{spec_preview}\n"
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
if total + len(block) > max_chars:
|
| 190 |
+
break
|
| 191 |
+
|
| 192 |
+
parts.append(block)
|
| 193 |
+
total += len(block)
|
| 194 |
+
|
| 195 |
+
parts.append("\nNow generate a specification for the following code:\n")
|
| 196 |
+
return "".join(parts)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def build_index(dataset_path: str = "data/training_pairs_clean.jsonl") -> None:
|
| 200 |
+
"""CLI entry point for building the vector index."""
|
| 201 |
+
retriever = SpecRetriever()
|
| 202 |
+
retriever.build_index(dataset_path)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
if __name__ == "__main__":
|
| 206 |
+
build_index()
|