Spaces:
Runtime error
Runtime error
Chris Wever | ONHN Claude Sonnet 4.6 commited on
Commit ·
eff1475
1
Parent(s): 932fbca
perf: parallelle LLM-reranking + min_score doorgifte
Browse files- matching.py: _rerank gebruikt ThreadPoolExecutor(max_workers=8)
pool=15 → ~4-6s, pool=100 → ~25s (was: 30s en 200s sequentieel)
- main.py: min_score doorgestuurd vanuit request (was hardcoded op 5)
fast pass min_score=0 werkt nu correct → geen resultaten meer gefilterd
- frontend: FAST_POOL 3→15, FULL_POOL 30→100 (terug naar originele kwaliteit)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- app/main.py +2 -1
- app/matching.py +186 -0
- frontend/index.html +2 -2
app/main.py
CHANGED
|
@@ -160,6 +160,7 @@ class MatchRequest(BaseModel):
|
|
| 160 |
filters: Optional[Dict[str, Any]] = Field(default=None, description="Optionele filters, bv {'is_bouw': true}")
|
| 161 |
top_n: Optional[int] = Field(default=None, description="Aantal resultaten")
|
| 162 |
pool_size: Optional[int] = Field(default=None, description="Aantal kandidaten voor LLM-rerank")
|
|
|
|
| 163 |
type_filter: Optional[List[str]] = Field(
|
| 164 |
default=None,
|
| 165 |
description="Voor kennispartners: filter op type. Bv ['Universiteit', 'TO2']"
|
|
@@ -214,7 +215,7 @@ def match(req: MatchRequest):
|
|
| 214 |
filters=req.filters,
|
| 215 |
pool_size=req.pool_size or DEFAULT_POOL_SIZE,
|
| 216 |
top_n=top_n,
|
| 217 |
-
min_score=DEFAULT_MIN_LLM_SCORE,
|
| 218 |
min_embedding_sim=DEFAULT_MIN_EMBEDDING_SIM,
|
| 219 |
)
|
| 220 |
return {"results": results, "n_results": len(results)}
|
|
|
|
| 160 |
filters: Optional[Dict[str, Any]] = Field(default=None, description="Optionele filters, bv {'is_bouw': true}")
|
| 161 |
top_n: Optional[int] = Field(default=None, description="Aantal resultaten")
|
| 162 |
pool_size: Optional[int] = Field(default=None, description="Aantal kandidaten voor LLM-rerank")
|
| 163 |
+
min_score: Optional[int] = Field(default=None, description="Minimum LLM-score (0-10)")
|
| 164 |
type_filter: Optional[List[str]] = Field(
|
| 165 |
default=None,
|
| 166 |
description="Voor kennispartners: filter op type. Bv ['Universiteit', 'TO2']"
|
|
|
|
| 215 |
filters=req.filters,
|
| 216 |
pool_size=req.pool_size or DEFAULT_POOL_SIZE,
|
| 217 |
top_n=top_n,
|
| 218 |
+
min_score=req.min_score if req.min_score is not None else DEFAULT_MIN_LLM_SCORE,
|
| 219 |
min_embedding_sim=DEFAULT_MIN_EMBEDDING_SIM,
|
| 220 |
)
|
| 221 |
return {"results": results, "n_results": len(results)}
|
app/matching.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Matching engine: hybride embeddings + LLM-reranker.
|
| 3 |
+
|
| 4 |
+
Architectuur:
|
| 5 |
+
1. Query wordt gecomponeerd uit chain_goal + role + detail
|
| 6 |
+
2. Embedding-similarity tegen alle 4099 bedrijven
|
| 7 |
+
3. Top-pool_size bedrijven worden doorgegeven aan Claude Haiku 4.5 reranker
|
| 8 |
+
4. LLM beoordeelt semantische fit met wereldkennis (materiaal-inferenties)
|
| 9 |
+
5. Resultaten boven min_score worden teruggegeven
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import concurrent.futures
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pandas as pd
|
| 16 |
+
from typing import Optional
|
| 17 |
+
from anthropic import Anthropic
|
| 18 |
+
from sentence_transformers import SentenceTransformer
|
| 19 |
+
|
| 20 |
+
from app.config import (
|
| 21 |
+
RERANK_MODEL,
|
| 22 |
+
RERANK_SYSTEM_PROMPT,
|
| 23 |
+
RERANK_USER_TEMPLATE,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class MatchingEngine:
|
| 28 |
+
"""Stateful matching engine. Wordt één keer geïnitialiseerd bij app startup."""
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
relevant_df: pd.DataFrame,
|
| 33 |
+
embeddings: np.ndarray,
|
| 34 |
+
model: SentenceTransformer,
|
| 35 |
+
anthropic_client: Anthropic,
|
| 36 |
+
):
|
| 37 |
+
self.relevant = relevant_df.reset_index(drop=True)
|
| 38 |
+
self.embeddings = embeddings
|
| 39 |
+
self.model = model
|
| 40 |
+
self.client = anthropic_client
|
| 41 |
+
|
| 42 |
+
if len(self.relevant) != len(self.embeddings):
|
| 43 |
+
raise ValueError(
|
| 44 |
+
f"Mismatch: {len(self.relevant)} bedrijven maar "
|
| 45 |
+
f"{len(self.embeddings)} embeddings"
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def match(
|
| 49 |
+
self,
|
| 50 |
+
chain_goal: str,
|
| 51 |
+
role: str,
|
| 52 |
+
detail: str = "",
|
| 53 |
+
filters: Optional[dict] = None,
|
| 54 |
+
pool_size: int = 100,
|
| 55 |
+
top_n: int = 20,
|
| 56 |
+
min_score: int = 5,
|
| 57 |
+
min_embedding_sim: float = 0.25,
|
| 58 |
+
) -> list[dict]:
|
| 59 |
+
"""
|
| 60 |
+
Voer een volledige match uit: embedding-search + LLM-rerank.
|
| 61 |
+
|
| 62 |
+
Returnt lijst van dicts met company_name, hq_municipality, llm_score,
|
| 63 |
+
llm_reason, embedding_sim, en alle relevante bedrijfsvelden.
|
| 64 |
+
"""
|
| 65 |
+
# 1. Build composite query
|
| 66 |
+
query_parts = [f"Keten: {chain_goal}", f"Rol in deze keten: {role}"]
|
| 67 |
+
if detail:
|
| 68 |
+
query_parts.append(f"Specifiek: {detail}")
|
| 69 |
+
query_text = ". ".join(query_parts)
|
| 70 |
+
|
| 71 |
+
# 2. Embedding similarity over hele dataset
|
| 72 |
+
q_emb = self.model.encode([query_text], normalize_embeddings=True)[0]
|
| 73 |
+
similarities = self.embeddings @ q_emb
|
| 74 |
+
|
| 75 |
+
# 3. Bouw kandidaten-dataframe met similarities
|
| 76 |
+
candidates = self.relevant.copy()
|
| 77 |
+
candidates["embedding_sim"] = similarities
|
| 78 |
+
|
| 79 |
+
# 4. Apply boolean filters (bv. {"is_bouw": True})
|
| 80 |
+
if filters:
|
| 81 |
+
for col, val in filters.items():
|
| 82 |
+
if col in candidates.columns:
|
| 83 |
+
target = str(val).lower()
|
| 84 |
+
candidates = candidates[
|
| 85 |
+
candidates[col].astype(str).str.lower() == target
|
| 86 |
+
]
|
| 87 |
+
|
| 88 |
+
# 5. Filter op minimum embedding similarity
|
| 89 |
+
candidates = candidates[candidates["embedding_sim"] >= min_embedding_sim]
|
| 90 |
+
|
| 91 |
+
# 6. Sorteer op similarity en neem pool
|
| 92 |
+
candidates = candidates.sort_values(
|
| 93 |
+
"embedding_sim", ascending=False
|
| 94 |
+
).head(pool_size)
|
| 95 |
+
|
| 96 |
+
if len(candidates) == 0:
|
| 97 |
+
return []
|
| 98 |
+
|
| 99 |
+
# 7. LLM rerank op elk in de pool
|
| 100 |
+
reranked = self._rerank(
|
| 101 |
+
candidates, chain_goal, role, detail
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# 8. Filter op min_score en geef top_n terug
|
| 105 |
+
above_threshold = [r for r in reranked if r["llm_score"] >= min_score]
|
| 106 |
+
above_threshold.sort(key=lambda x: x["llm_score"], reverse=True)
|
| 107 |
+
|
| 108 |
+
return above_threshold[:top_n]
|
| 109 |
+
|
| 110 |
+
def _rerank_one(self, row: pd.Series, chain_goal: str, role: str, detail: str) -> dict:
|
| 111 |
+
"""Rerank één kandidaat met Claude Haiku (thread-safe)."""
|
| 112 |
+
user_prompt = RERANK_USER_TEMPLATE.format(
|
| 113 |
+
chain_goal=chain_goal,
|
| 114 |
+
role=role,
|
| 115 |
+
detail=detail,
|
| 116 |
+
name=str(row.get("company_name", "")),
|
| 117 |
+
industry=str(row.get("industry", "")),
|
| 118 |
+
summary=str(row.get("samenvatting_llm", ""))[:500],
|
| 119 |
+
competencies=str(row.get("kern_competenties", ""))[:300],
|
| 120 |
+
products=str(row.get("producten_diensten", ""))[:300],
|
| 121 |
+
domains=str(row.get("toepassingsdomeinen", ""))[:200],
|
| 122 |
+
materials=str(row.get("gebruikte_materialen", ""))[:200],
|
| 123 |
+
value_chain_role=str(row.get("value_chain_role", "")),
|
| 124 |
+
product_type=str(row.get("product_type", "")),
|
| 125 |
+
circular_profile=str(row.get("circulair_profiel", "")),
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
response = self.client.messages.create(
|
| 130 |
+
model=RERANK_MODEL,
|
| 131 |
+
max_tokens=200,
|
| 132 |
+
system=RERANK_SYSTEM_PROMPT,
|
| 133 |
+
messages=[{"role": "user", "content": user_prompt}],
|
| 134 |
+
)
|
| 135 |
+
text = response.content[0].text.strip()
|
| 136 |
+
if text.startswith("```"):
|
| 137 |
+
text = text.split("```")[1]
|
| 138 |
+
if text.startswith("json"):
|
| 139 |
+
text = text[4:]
|
| 140 |
+
text = text.strip()
|
| 141 |
+
parsed = json.loads(text)
|
| 142 |
+
llm_score = int(parsed.get("fit_score", 0))
|
| 143 |
+
llm_reason = str(parsed.get("reason", ""))
|
| 144 |
+
except Exception as e:
|
| 145 |
+
llm_score = 0
|
| 146 |
+
llm_reason = f"Rerank error: {str(e)[:80]}"
|
| 147 |
+
|
| 148 |
+
return {
|
| 149 |
+
"company_name": str(row.get("company_name", "")),
|
| 150 |
+
"hq_municipality": str(row.get("hq_municipality", "")),
|
| 151 |
+
"deelregio": str(row.get("deelregio", "")),
|
| 152 |
+
"industry": str(row.get("industry", "")),
|
| 153 |
+
"samenvatting_llm": str(row.get("samenvatting_llm", "")),
|
| 154 |
+
"kern_competenties": str(row.get("kern_competenties", "")),
|
| 155 |
+
"producten_diensten": str(row.get("producten_diensten", "")),
|
| 156 |
+
"toepassingsdomeinen": str(row.get("toepassingsdomeinen", "")),
|
| 157 |
+
"circulair_profiel": str(row.get("circulair_profiel", "")),
|
| 158 |
+
"linkedin_url": str(row.get("linkedin_url", "")),
|
| 159 |
+
"is_bouw": bool(str(row.get("is_bouw", "")).lower() == "true"),
|
| 160 |
+
"is_biobased": bool(str(row.get("is_biobased", "")).lower() == "true"),
|
| 161 |
+
"is_maritiem": bool(str(row.get("is_maritiem", "")).lower() == "true"),
|
| 162 |
+
"is_textiel": bool(str(row.get("is_textiel", "")).lower() == "true"),
|
| 163 |
+
"is_agri": bool(str(row.get("is_agri", "")).lower() == "true"),
|
| 164 |
+
"is_energie": bool(str(row.get("is_energie", "")).lower() == "true"),
|
| 165 |
+
"embedding_sim": float(row["embedding_sim"]),
|
| 166 |
+
"llm_score": llm_score,
|
| 167 |
+
"llm_reason": llm_reason,
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
def _rerank(
|
| 171 |
+
self,
|
| 172 |
+
candidates_df: pd.DataFrame,
|
| 173 |
+
chain_goal: str,
|
| 174 |
+
role: str,
|
| 175 |
+
detail: str,
|
| 176 |
+
max_workers: int = 8,
|
| 177 |
+
) -> list[dict]:
|
| 178 |
+
"""Rerank alle kandidaten parallel met Claude Haiku (8 threads)."""
|
| 179 |
+
rows = [row for _, row in candidates_df.iterrows()]
|
| 180 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 181 |
+
futures = [
|
| 182 |
+
executor.submit(self._rerank_one, row, chain_goal, role, detail)
|
| 183 |
+
for row in rows
|
| 184 |
+
]
|
| 185 |
+
results = [f.result() for f in futures]
|
| 186 |
+
return results
|
frontend/index.html
CHANGED
|
@@ -1969,8 +1969,8 @@ function acceptGeneratedChain(vraagstuk, result) {
|
|
| 1969 |
================================================================ */
|
| 1970 |
|
| 1971 |
/* pool_size = aantal LLM-calls; fast is beperkt voor snelheid, full voor kwaliteit */
|
| 1972 |
-
const FAST_POOL =
|
| 1973 |
-
const FULL_POOL =
|
| 1974 |
|
| 1975 |
async function loadAndMatchChain(chain) {
|
| 1976 |
const empty = document.getElementById('keten-empty');
|
|
|
|
| 1969 |
================================================================ */
|
| 1970 |
|
| 1971 |
/* pool_size = aantal LLM-calls; fast is beperkt voor snelheid, full voor kwaliteit */
|
| 1972 |
+
const FAST_POOL = 15; // parallel: 15 calls / 8 threads → ~4-6s eerste resultaten
|
| 1973 |
+
const FULL_POOL = 100; // parallel: 100 calls / 8 threads → ~25s volledige kwaliteit
|
| 1974 |
|
| 1975 |
async function loadAndMatchChain(chain) {
|
| 1976 |
const empty = document.getElementById('keten-empty');
|