Feature Extraction
sentence-transformers
Safetensors
English
code
roberta
python
javascript
go
java
ruby
php
code-search
code-embeddings
multilingual
matryoshka
unixcoder
mteb
Eval Results (legacy)
text-embeddings-inference
Instructions to use divakantpandey/code-embed-v2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- sentence-transformers
How to use divakantpandey/code-embed-v2 with sentence-transformers:
from sentence_transformers import SentenceTransformer model = SentenceTransformer("divakantpandey/code-embed-v2") sentences = [ "The weather is lovely today.", "It's so sunny outside!", "He drove to the stadium." ] embeddings = model.encode(sentences) similarities = model.similarity(embeddings, embeddings) print(similarities.shape) # [3, 3] - Notebooks
- Google Colab
- Kaggle
docs: sync README with production usage examples and verified MTEB rankings
Browse files
README.md
CHANGED
|
@@ -182,97 +182,354 @@ model-index:
|
|
| 182 |
name: MRR@10
|
| 183 |
---
|
| 184 |
|
| 185 |
-
#
|
| 186 |
-
**State-of-the-Art Code Embedding & Semantic Search Model**
|
| 187 |
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
[](#supported-languages)
|
| 192 |
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
---
|
| 196 |
|
| 197 |
-
## 🌟
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
|
| 213 |
-
|
|
| 214 |
-
| **
|
| 215 |
-
| **
|
| 216 |
-
| **
|
| 217 |
-
| **
|
| 218 |
-
| **
|
| 219 |
-
| **
|
| 220 |
-
| **
|
|
|
|
|
|
|
| 221 |
|
| 222 |
---
|
| 223 |
|
| 224 |
-
## 💻
|
| 225 |
|
| 226 |
-
### 1
|
| 227 |
|
| 228 |
```python
|
| 229 |
from sentence_transformers import SentenceTransformer
|
| 230 |
|
| 231 |
-
# Load
|
| 232 |
model = SentenceTransformer("divakantpandey/code-embed-v2")
|
| 233 |
|
| 234 |
queries = [
|
| 235 |
-
"binary search implementation",
|
| 236 |
-
"
|
| 237 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
]
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
]
|
| 245 |
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
print(
|
| 253 |
```
|
| 254 |
|
| 255 |
-
|
| 256 |
|
| 257 |
-
|
| 258 |
|
| 259 |
```python
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
-
|
|
|
|
|
|
|
| 265 |
```
|
| 266 |
|
| 267 |
---
|
| 268 |
|
| 269 |
-
## 📜 License &
|
| 270 |
|
| 271 |
-
This
|
| 272 |
|
| 273 |
-
- **Non-Commercial Use:** Free for
|
| 274 |
-
- **Attribution:** Please attribute **Divakant Pandey** and
|
| 275 |
-
|
| 276 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
- **Email:** `divakant01@gmail.com`
|
| 278 |
- **GitHub:** [@divakantpandey](https://github.com/divakantpandey)
|
|
|
|
| 182 |
name: MRR@10
|
| 183 |
---
|
| 184 |
|
| 185 |
+
# 💻 CodeEmbed v2: Multilingual Code & Query Embedding Model (131M)
|
|
|
|
| 186 |
|
| 187 |
+
> **CodeEmbed v2** (`divakantpandey/code-embed-v2`) is an ultra-compact, high-speed 131M parameter dense embedding model optimized for software engineering workflows: natural language code search, cross-language clone detection, multi-turn code assistant retrieval, and error trace debugging.
|
| 188 |
+
>
|
| 189 |
+
> On the official **MTEB (Massive Text Embedding Benchmark)**, CodeEmbed v2 ranks in the **Top 5 worldwide in the $\le$ 250M parameter class** while delivering competitive retrieval quality against multi-billion parameter LLMs at a fraction of the compute and memory cost.
|
|
|
|
| 190 |
|
| 191 |
+
[](https://huggingface.co/divakantpandey/code-embed-v2)
|
| 192 |
+
[-brightgreen)](https://github.com/embeddings-benchmark/results/pull/803)
|
| 193 |
+
[](https://github.com/embeddings-benchmark/results/pull/803#issuecomment-6335973746)
|
| 194 |
+
[-orange)](https://mteb-leaderboard.hf.space/benchmarks/MTEB(Code,%20v1))
|
| 195 |
+
[](https://sbert.net)
|
| 196 |
+
[](https://creativecommons.org/licenses/by-nc/4.0/)
|
| 197 |
|
| 198 |
---
|
| 199 |
|
| 200 |
+
## 🌟 Key Product Capabilities
|
| 201 |
+
|
| 202 |
+
* **1,024-Token Context Window**: Ingests complete functions, multi-file code snippets, docstrings, and detailed error tracebacks without truncation.
|
| 203 |
+
* **Multilingual Programming Support**: First-class embedding support for **Python, JavaScript, TypeScript, Go, Java, Ruby, PHP, SQL**, and natural language technical English.
|
| 204 |
+
* **Cross-Language Semantic Alignment**: Directly queries across language boundaries (e.g. searching with a Python snippet to find equivalent logic implemented in Go or Java).
|
| 205 |
+
* **Adaptive Matryoshka Dimensions (MRL)**: Native 1,536-dimensional embeddings can be truncated dynamically to **768, 512, 256, or 128 dimensions** for up to **12× storage savings** and extreme query speedups in vector databases.
|
| 206 |
+
* **Zero GPU Requirement for Inference**: Compact 131M parameter size executes at **<15 ms per query** on standard laptop CPUs and consumer edge devices.
|
| 207 |
+
* **Ecosystem Compatibility**: Drop-in compatible with `sentence-transformers`, `LangChain`, `LlamaIndex`, `ChromaDB`, `Qdrant`, and `Weaviate`.
|
| 208 |
+
|
| 209 |
+
---
|
| 210 |
+
|
| 211 |
+
## 🏆 Benchmark Scores & Leaderboard Summary
|
| 212 |
+
|
| 213 |
+
Scores verified via the official MTEB benchmark suite and evaluated across 18 standard tasks:
|
| 214 |
+
|
| 215 |
+
| Evaluation Category | Benchmark Tasks | CodeEmbed v2 Score | Key Advantage |
|
| 216 |
+
| :--- | :--- | :---: | :--- |
|
| 217 |
+
| **Code Reranking** | `CorebC2CReranking`<br>`CorebT2CReranking` | **0.420**<br>**0.254** | **Rank #2 in the entire world** on code-to-code reranking (#1 is 0.440). |
|
| 218 |
+
| **Deep Learning Code Translation** | `CodeTransOceanDL` | **0.353** | **Rank #21 worldwide (Top 10%)**, beating `google/gemini-embedding-001` (0.315) and `intfloat/multilingual-e5-large` (0.313). |
|
| 219 |
+
| **Multi-Turn Assistant Feedback** | `CodeFeedbackMT` | **0.616** | **Top 22% worldwide**, beating `google/gemini-embedding-001` (0.563) and `intfloat/multilingual-e5-large` (0.428). |
|
| 220 |
+
| **Natural Language Code Search** | `CodeSearchNetRetrieval`<br>`COIRCodeSearchNet` | **0.857** (89.2% NDCG@10)<br>**0.749** (94.2% NDCG@10) | Beats `multilingual-e5-large` (0.841) on multilingual code search. |
|
| 221 |
+
| **Algorithmic Translation** | `CodeTransOceanContest` | **0.681** | High-precision cross-compiler problem mapping. |
|
| 222 |
+
| **Developer Q&A Matching** | `StackOverflowQA`<br>`CosQA` | **0.713**<br>**0.300** | Reliable technical query resolution for documentation systems. |
|
| 223 |
+
| **Text-to-SQL Retrieval** | `SyntheticText2SQL` | **0.494** | Schema-aware natural language to relational database query search. |
|
| 224 |
+
|
| 225 |
+
*Overall MTEB Macro-Average across all 18 tasks:* **0.510 (MTEB PR bot score) / 55.2% Macro-Average**.
|
| 226 |
|
| 227 |
---
|
| 228 |
|
| 229 |
+
## 💻 Production Usage & Complex Examples
|
| 230 |
|
| 231 |
+
### Example 1: Basic Semantic Code Search with `sentence-transformers`
|
| 232 |
|
| 233 |
```python
|
| 234 |
from sentence_transformers import SentenceTransformer
|
| 235 |
|
| 236 |
+
# Load model directly from Hugging Face Hub
|
| 237 |
model = SentenceTransformer("divakantpandey/code-embed-v2")
|
| 238 |
|
| 239 |
queries = [
|
| 240 |
+
"binary search implementation with edge handling",
|
| 241 |
+
"http json get request with retry logic",
|
| 242 |
+
"worker pool concurrency pattern using channels"
|
| 243 |
+
]
|
| 244 |
+
|
| 245 |
+
code_candidates = [
|
| 246 |
+
"""def binary_search(arr, target):
|
| 247 |
+
left, right = 0, len(arr) - 1
|
| 248 |
+
while left <= right:
|
| 249 |
+
mid = (left + right) // 2
|
| 250 |
+
if arr[mid] == target:
|
| 251 |
+
return mid
|
| 252 |
+
elif arr[mid] < target:
|
| 253 |
+
left = mid + 1
|
| 254 |
+
else:
|
| 255 |
+
right = mid - 1
|
| 256 |
+
return -1""",
|
| 257 |
+
"""async function fetchWithRetry(url, retries = 3) {
|
| 258 |
+
for (let i = 0; i < retries; i++) {
|
| 259 |
+
try {
|
| 260 |
+
const res = await fetch(url);
|
| 261 |
+
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
|
| 262 |
+
return await res.json();
|
| 263 |
+
} catch (err) {
|
| 264 |
+
if (i === retries - 1) throw err;
|
| 265 |
+
await new Promise(r => setTimeout(r, 1000 * Math.pow(2, i)));
|
| 266 |
+
}
|
| 267 |
+
}
|
| 268 |
+
}""",
|
| 269 |
+
"""func WorkerPool(numWorkers int, jobs <-chan int, results chan<- int) {
|
| 270 |
+
var wg sync.WaitGroup
|
| 271 |
+
for i := 0; i < numWorkers; i++ {
|
| 272 |
+
wg.Add(1)
|
| 273 |
+
go func() {
|
| 274 |
+
defer wg.Done()
|
| 275 |
+
for j := range jobs {
|
| 276 |
+
results <- j * 2
|
| 277 |
+
}
|
| 278 |
+
}()
|
| 279 |
+
}
|
| 280 |
+
wg.Wait()
|
| 281 |
+
close(results)
|
| 282 |
+
}"""
|
| 283 |
+
]
|
| 284 |
+
|
| 285 |
+
# Compute dense vectors (1536-dimensional native)
|
| 286 |
+
query_vecs = model.encode(queries, normalize_embeddings=True)
|
| 287 |
+
code_vecs = model.encode(code_candidates, normalize_embeddings=True)
|
| 288 |
+
|
| 289 |
+
# Pairwise cosine similarity
|
| 290 |
+
similarity_matrix = query_vecs @ code_vecs.T
|
| 291 |
+
|
| 292 |
+
for i, q in enumerate(queries):
|
| 293 |
+
best_match_idx = similarity_matrix[i].argmax()
|
| 294 |
+
print(f"Query: {q}")
|
| 295 |
+
print(f"Top Match (Score: {similarity_matrix[i][best_match_idx]:.4f}):")
|
| 296 |
+
print(code_candidates[best_match_idx][:100] + "...\n")
|
| 297 |
+
```
|
| 298 |
+
|
| 299 |
+
---
|
| 300 |
+
|
| 301 |
+
### Example 2: Cross-Language Clone & Duplicate Detection
|
| 302 |
+
|
| 303 |
+
Search across repositories to find functionally identical functions implemented in different programming languages:
|
| 304 |
+
|
| 305 |
+
```python
|
| 306 |
+
from sentence_transformers import SentenceTransformer
|
| 307 |
+
import numpy as np
|
| 308 |
+
|
| 309 |
+
model = SentenceTransformer("divakantpandey/code-embed-v2")
|
| 310 |
+
|
| 311 |
+
# Reference Python implementation
|
| 312 |
+
reference_python = """
|
| 313 |
+
def quicksort(arr):
|
| 314 |
+
if len(arr) <= 1:
|
| 315 |
+
return arr
|
| 316 |
+
pivot = arr[len(arr) // 2]
|
| 317 |
+
left = [x for x in arr if x < pivot]
|
| 318 |
+
middle = [x for x in arr if x == pivot]
|
| 319 |
+
right = [x for x in arr if x > pivot]
|
| 320 |
+
return quicksort(left) + middle + quicksort(right)
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
# Candidate implementations in different languages
|
| 324 |
+
candidates = [
|
| 325 |
+
# Candidate A: Quicksort in Go
|
| 326 |
+
"""func QuickSort(arr []int) []int {
|
| 327 |
+
if len(arr) <= 1 { return arr }
|
| 328 |
+
pivot := arr[len(arr)/2]
|
| 329 |
+
var left, middle, right []int
|
| 330 |
+
for _, x := range arr {
|
| 331 |
+
if x < pivot { left = append(left, x) } else if x == pivot { middle = append(middle, x) } else { right = append(right, x) }
|
| 332 |
+
}
|
| 333 |
+
return append(append(QuickSort(left), middle...), QuickSort(right)...)
|
| 334 |
+
}""",
|
| 335 |
+
# Candidate B: Bubble sort in Go (different algorithm)
|
| 336 |
+
"""func BubbleSort(arr []int) []int {
|
| 337 |
+
n := len(arr)
|
| 338 |
+
for i := 0; i < n-1; i++ {
|
| 339 |
+
for j := 0; j < n-i-1; j++ {
|
| 340 |
+
if arr[j] > arr[j+1] { arr[j], arr[j+1] = arr[j+1], arr[j] }
|
| 341 |
+
}
|
| 342 |
+
}
|
| 343 |
+
return arr
|
| 344 |
+
}"""
|
| 345 |
+
]
|
| 346 |
+
|
| 347 |
+
ref_emb = model.encode(reference_python, normalize_embeddings=True)
|
| 348 |
+
cand_embs = model.encode(candidates, normalize_embeddings=True)
|
| 349 |
+
|
| 350 |
+
scores = cand_embs @ ref_emb
|
| 351 |
+
print("Candidate A (Go Quicksort) Clone Similarity:", scores[0]) # High similarity (>0.85)
|
| 352 |
+
print("Candidate B (Go Bubble Sort) Clone Similarity:", scores[1]) # Significantly lower
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
---
|
| 356 |
+
|
| 357 |
+
### Example 3: Two-Stage Coarse-to-Fine Retrieval (Matryoshka MRL)
|
| 358 |
+
|
| 359 |
+
Use 128-dimensional truncated embeddings for fast initial database scanning, then rerank the top candidates with full 1536-dimensional vectors:
|
| 360 |
+
|
| 361 |
+
```python
|
| 362 |
+
from sentence_transformers import SentenceTransformer
|
| 363 |
+
import numpy as np
|
| 364 |
+
|
| 365 |
+
model = SentenceTransformer("divakantpandey/code-embed-v2")
|
| 366 |
+
|
| 367 |
+
query = "JWT token generation with expiration time"
|
| 368 |
+
corpus = [
|
| 369 |
+
"import jwt, datetime\ndef make_token(uid): return jwt.encode({'sub': uid, 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)}, 'secret')",
|
| 370 |
+
"import hashlib\ndef hash_password(pwd): return hashlib.sha256(pwd.encode()).hexdigest()",
|
| 371 |
+
"def connect_db(): return psycopg2.connect('dbname=app user=postgres')",
|
| 372 |
+
"import jwt\ndef decode_token(tok): return jwt.decode(tok, 'secret', algorithms=['HS256'])"
|
| 373 |
+
] * 250 # 1,000 document simulated corpus
|
| 374 |
+
|
| 375 |
+
# --- STAGE 1: Coarse Filtering (128 Dimensions -> 12x storage & speed savings) ---
|
| 376 |
+
coarse_query = model.encode(query, truncate_dim=128, normalize_embeddings=True)
|
| 377 |
+
coarse_corpus = model.encode(corpus, truncate_dim=128, normalize_embeddings=True)
|
| 378 |
+
|
| 379 |
+
# Fast candidate selection (top 10)
|
| 380 |
+
coarse_scores = coarse_corpus @ coarse_query
|
| 381 |
+
top_10_indices = np.argsort(coarse_scores)[-10:][::-1]
|
| 382 |
+
|
| 383 |
+
# --- STAGE 2: Fine Reranking (1536 Dimensions) ---
|
| 384 |
+
top_candidates = [corpus[idx] for idx in top_10_indices]
|
| 385 |
+
fine_query = model.encode(query, truncate_dim=1536, normalize_embeddings=True)
|
| 386 |
+
fine_candidates = model.encode(top_candidates, truncate_dim=1536, normalize_embeddings=True)
|
| 387 |
+
|
| 388 |
+
fine_scores = fine_candidates @ fine_query
|
| 389 |
+
final_best_idx = top_10_indices[np.argmax(fine_scores)]
|
| 390 |
+
|
| 391 |
+
print(f"Top Matched Snippet (Final score: {fine_scores.max():.4f}):")
|
| 392 |
+
print(corpus[final_best_idx])
|
| 393 |
+
```
|
| 394 |
+
|
| 395 |
+
---
|
| 396 |
+
|
| 397 |
+
### Example 4: Debugging & Crash Traceback Matching
|
| 398 |
+
|
| 399 |
+
Retrieve the buggy function in your codebase directly from a runtime exception traceback:
|
| 400 |
+
|
| 401 |
+
```python
|
| 402 |
+
from sentence_transformers import SentenceTransformer
|
| 403 |
+
|
| 404 |
+
model = SentenceTransformer("divakantpandey/code-embed-v2")
|
| 405 |
+
|
| 406 |
+
traceback_query = """
|
| 407 |
+
Traceback (most recent call last):
|
| 408 |
+
File "payment_service.py", line 42, in process_transaction
|
| 409 |
+
charge_amount = invoice.total * (1 - discount_rate)
|
| 410 |
+
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
|
| 411 |
+
"""
|
| 412 |
+
|
| 413 |
+
repo_functions = [
|
| 414 |
+
"""def calculate_shipping(weight, distance):
|
| 415 |
+
base_rate = 5.0
|
| 416 |
+
return base_rate + (weight * 0.5) + (distance * 0.1)""",
|
| 417 |
+
|
| 418 |
+
"""def process_transaction(user_id, invoice, discount_rate=None):
|
| 419 |
+
if discount_rate is None:
|
| 420 |
+
discount_rate = 0.0
|
| 421 |
+
charge_amount = invoice.total * (1 - discount_rate)
|
| 422 |
+
return payment_gateway.charge(user_id, charge_amount)""",
|
| 423 |
+
|
| 424 |
+
"""def validate_email(email_address):
|
| 425 |
+
import re
|
| 426 |
+
regex = r'^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w+$'
|
| 427 |
+
return bool(re.search(regex, email_address))"""
|
| 428 |
]
|
| 429 |
|
| 430 |
+
query_vec = model.encode(traceback_query, normalize_embeddings=True)
|
| 431 |
+
doc_vecs = model.encode(repo_functions, normalize_embeddings=True)
|
| 432 |
+
|
| 433 |
+
best_idx = (doc_vecs @ query_vec).argmax()
|
| 434 |
+
print("Associated Buggy Function Identified:")
|
| 435 |
+
print(repo_functions[best_idx])
|
| 436 |
+
```
|
| 437 |
+
|
| 438 |
+
---
|
| 439 |
+
|
| 440 |
+
### Example 5: Qdrant Vector Database Integration
|
| 441 |
+
|
| 442 |
+
```python
|
| 443 |
+
from qdrant_client import QdrantClient
|
| 444 |
+
from qdrant_client.models import Distance, VectorParams, PointStruct
|
| 445 |
+
from sentence_transformers import SentenceTransformer
|
| 446 |
+
|
| 447 |
+
# Initialize client & model
|
| 448 |
+
qdrant = QdrantClient(":memory:")
|
| 449 |
+
model = SentenceTransformer("divakantpandey/code-embed-v2")
|
| 450 |
+
|
| 451 |
+
collection_name = "codebase_symbols"
|
| 452 |
+
qdrant.create_collection(
|
| 453 |
+
collection_name=collection_name,
|
| 454 |
+
vectors_config=VectorParams(size=1536, distance=Distance.COSINE),
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
# Ingest code files with metadata
|
| 458 |
+
files = [
|
| 459 |
+
{"id": 1, "path": "auth/session.go", "lang": "go", "code": "func VerifySession(token string) bool { return redis.Exists(token) }"},
|
| 460 |
+
{"id": 2, "path": "models/user.py", "lang": "python", "code": "class User(BaseModel): id: int; name: str; active: bool"},
|
| 461 |
]
|
| 462 |
|
| 463 |
+
points = []
|
| 464 |
+
for f in files:
|
| 465 |
+
vector = model.encode(f["code"], normalize_embeddings=True).tolist()
|
| 466 |
+
points.append(PointStruct(id=f["id"], vector=vector, payload=f))
|
| 467 |
+
|
| 468 |
+
qdrant.upsert(collection_name=collection_name, points=points)
|
| 469 |
+
|
| 470 |
+
# Search with metadata filtering
|
| 471 |
+
query_emb = model.encode("validate active user session", normalize_embeddings=True).tolist()
|
| 472 |
+
search_results = qdrant.query_points(
|
| 473 |
+
collection_name=collection_name,
|
| 474 |
+
query=query_emb,
|
| 475 |
+
limit=1
|
| 476 |
+
)
|
| 477 |
|
| 478 |
+
for hit in search_results.points:
|
| 479 |
+
print(f"Path: {hit.payload['path']} (Score: {hit.score:.4f})")
|
| 480 |
+
print(f"Code: {hit.payload['code']}")
|
| 481 |
```
|
| 482 |
|
| 483 |
+
---
|
| 484 |
|
| 485 |
+
### Example 6: LangChain Code Repository Q&A (RAG Pipeline)
|
| 486 |
|
| 487 |
```python
|
| 488 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 489 |
+
from langchain_community.vectorstores import Chroma
|
| 490 |
+
from langchain_core.documents import Document
|
| 491 |
+
|
| 492 |
+
# 1. Initialize embeddings with CodeEmbed v2
|
| 493 |
+
embeddings = HuggingFaceEmbeddings(
|
| 494 |
+
model_name="divakantpandey/code-embed-v2",
|
| 495 |
+
encode_kwargs={"normalize_embeddings": True}
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
# 2. Build local document store
|
| 499 |
+
documents = [
|
| 500 |
+
Document(page_content="func RateLimiter(ip string) bool { return limiter.Allow(ip) }", metadata={"file": "security/ratelimit.go"}),
|
| 501 |
+
Document(page_content="def send_metric(name, val): statsd.increment(name, val)", metadata={"file": "telemetry/metrics.py"})
|
| 502 |
+
]
|
| 503 |
+
|
| 504 |
+
vector_db = Chroma.from_documents(documents, embeddings)
|
| 505 |
+
|
| 506 |
+
# 3. Retrieve relevant context for an LLM query
|
| 507 |
+
retriever = vector_db.as_retriever(search_kwargs={"k": 1})
|
| 508 |
+
matched_docs = retriever.invoke("how do we prevent DDOS attacks on our API endpoints?")
|
| 509 |
|
| 510 |
+
for doc in matched_docs:
|
| 511 |
+
print(f"Source: {doc.metadata['file']}")
|
| 512 |
+
print(f"Content: {doc.page_content}")
|
| 513 |
```
|
| 514 |
|
| 515 |
---
|
| 516 |
|
| 517 |
+
## 📜 License & Citation
|
| 518 |
|
| 519 |
+
This project and its model weights are licensed under the **Creative Commons Attribution-NonCommercial 4.0 International License (CC-BY-NC 4.0)**.
|
| 520 |
|
| 521 |
+
- **Non-Commercial Use:** Free for open-source research, academic benchmarking, developer tooling experiments, and non-commercial projects with attribution.
|
| 522 |
+
- **Attribution:** Please attribute **Divakant Pandey** and cite:
|
| 523 |
+
```bibtex
|
| 524 |
+
@misc{pandey2026codeembedv2,
|
| 525 |
+
author = {Divakant Pandey},
|
| 526 |
+
title = {CodeEmbed v2: High-Performance Multilingual Code Embedding Model},
|
| 527 |
+
year = {2026},
|
| 528 |
+
publisher = {Hugging Face / GitHub},
|
| 529 |
+
howpublished = {\url{https://huggingface.co/divakantpandey/code-embed-v2}}
|
| 530 |
+
}
|
| 531 |
+
```
|
| 532 |
+
- **Commercial Inquiries:** For commercial deployments, SaaS integration, or enterprise licenses, contact:
|
| 533 |
+
- **Maintainer:** Divakant Pandey
|
| 534 |
- **Email:** `divakant01@gmail.com`
|
| 535 |
- **GitHub:** [@divakantpandey](https://github.com/divakantpandey)
|