Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(skill): 基于经验增强的skill分发针对同一个query可能推送重复skill

chunbs_cbs01554109cfd1
diff --git a/jiuwenswarm/symphony/experience/cluster.py b/jiuwenswarm/symphony/experience/cluster.py
index 85d2ff0be4..ab5f14eb85 100644
--- a/jiuwenswarm/symphony/experience/cluster.py
+++ b/jiuwenswarm/symphony/experience/cluster.py
@@ -8,6 +8,7 @@ via FAISS K-Means (cosine distance).
from __future__ import annotations
import logging
+import random
from dataclasses import dataclass
import numpy as np
@@ -32,13 +33,15 @@ class ClusteredQuery:
def cluster_traces(
traces: list[TraceRecord],
embedder: EmbeddingClient,
+ n_clusters: int | None = None,
min_cluster_size: int = 1,
+ cluster_max_examples: int | None = None,
) -> list[ClusteredQuery]:
"""Cluster traces: first by skill set, then by semantic similarity.
1. Partition traces by their skill set (frozenset of skill_ids).
2. Within each group, embed queries and cluster via FAISS K-Means.
- 3. Split each semantic cluster into success / failure buckets.
+ 3. Split each semantic cluster into success buckets.
"""
if not traces:
return []
@@ -49,6 +52,8 @@ def cluster_traces(
key = frozenset(t.skills) if t.skills else frozenset()
skill_groups.setdefault(key, []).append(t)
+ sampler = random.Random(42)
+
result: list[ClusteredQuery] = []
cluster_id_counter = 0
@@ -57,14 +62,17 @@ def cluster_traces(
group_traces = skill_groups.get(skill_key, [])
if not group_traces:
continue
- queries = [t.query for t in group_traces]
+ successes = [t for t in group_traces if t.success]
+ if cluster_max_examples is not None:
+ cap = max(1, cluster_max_examples)
+ successes = (sampler.sample(successes, cap) if len(successes) > cap else successes)
+ queries = [t.query for t in successes]
embeddings = embedder.embed_batch(queries)
- # Use min_cluster_size=2 for FAISS so small groups still form clusters;
- # the outer `min_cluster_size` parameter controls discarding, not FAISS.
labels = _faiss_cluster(
embeddings,
max_iterations=50,
+ n_clusters=n_clusters,
min_cluster_size=min_cluster_size,
)
@@ -75,7 +83,7 @@ def cluster_traces(
for _local_id in sorted(local_clusters.keys()):
indices = local_clusters.get(_local_id, [])
- members = [group_traces[i] for i in indices]
+ members = [successes[i] for i in indices]
# Filter clusters smaller than the configured min_cluster_size
if len(members) < min_cluster_size:
@@ -95,7 +103,7 @@ def populate_cluster(
members: list[TraceRecord],
) -> ClusteredQuery:
success_traces = [t for t in members if t.success]
- failure_traces = [t for t in members if not t.success]
+ failure_traces = []
# Find centroid: member whose embedding is closest to the group mean
member_embeddings = np.array(
@@ -120,7 +128,7 @@ def _faiss_cluster(
*,
n_clusters: int | None = None,
max_iterations: int = 50,
- min_cluster_size: int = 2,
+ min_cluster_size: int = 1,
) -> list[int]:
"""Cluster embeddings using FAISS K-Means with cosine distance.
diff --git a/jiuwenswarm/symphony/experience/collector.py b/jiuwenswarm/symphony/experience/collector.py
index 41bb113d95..71401f2a5c 100644
--- a/jiuwenswarm/symphony/experience/collector.py
+++ b/jiuwenswarm/symphony/experience/collector.py
@@ -1,17 +1,19 @@
from __future__ import annotations
import logging
+import random
import threading
import time
from collections import defaultdict
from typing import Any
-from . import ExperienceBank
+import numpy as np
+
from .bank import ExperienceBank
from .cluster import ClusteredQuery, cluster_traces, _faiss_cluster, populate_cluster
from .distiller import TraceDistiller
from .embed import EmbeddingClient
-from .models import ExperienceBankBuildConfig, ExperienceItem, TraceRecord
+from .models import ExperienceBankBuildConfig, DistilledPattern, ExperienceItem, TraceRecord
LOGGER = logging.getLogger(__name__)
@@ -47,6 +49,10 @@ class ExperienceBaseBuilder:
self._pending: list[TraceRecord] = []
self._flush_threshold = self._config.pending_flush_threshold
self._min_hits = self._config.min_hits_for_pattern
+ self._pattern_merge_threshold = self._config.pattern_merge_threshold
+ self._query_examples_count = self._config.query_examples_count
+ self._skill_cluster_num = self._config.skill_cluster_num
+ self._cluster_max_examples = self._config.cluster_max_examples
self._lock = threading.Lock()
def build(self, traces: list[TraceRecord]) -> int:
@@ -84,7 +90,12 @@ class ExperienceBaseBuilder:
# --- Cluster ---
t1 = time.monotonic()
- clusters = cluster_traces(traces, self._embedder, self._min_cluster_size)
+ clusters = cluster_traces(
+ traces, self._embedder,
+ n_clusters=self._skill_cluster_num,
+ min_cluster_size=self._min_cluster_size,
+ cluster_max_examples=self._cluster_max_examples,
+ )
cluster_elapsed = time.monotonic() - t1
LOGGER.info(
"TraceIndexBuilder: clustering done: %d clusters in %.2fs",
@@ -114,20 +125,31 @@ class ExperienceBaseBuilder:
# --- Write to KB ---
t3 = time.monotonic()
cluster_by_id = {c.cluster_id: c for c in clusters}
- batch_items = []
-
- for pattern in distilled:
- if not pattern.pattern_description:
- continue
- top_skills = pattern.effective_skills[0] if pattern.effective_skills else []
+ valid_patterns = [p for p in distilled if p.pattern_description]
+ merged_patterns = self._merge_similar_patterns(valid_patterns, cluster_by_id)
+ batch_items = []
+ sample_n = max(0, self._query_examples_count)
+ rng = random.Random(42)
+ for pattern in merged_patterns:
+ top_skills = pattern.effective_skills if pattern.effective_skills else []
cluster = cluster_by_id.get(pattern.cluster_id)
- examples = [trace.query for trace in cluster.success_traces] if cluster else [pattern.pattern_description]
+ examples = (
+ [trace.query for trace in cluster.success_traces]
+ if cluster
+ else [pattern.pattern_description]
+ )
+ if sample_n == 0:
+ sampled = []
+ elif len(examples) > sample_n:
+ sampled = rng.sample(examples, sample_n)
+ else:
+ sampled = list(examples)
item = self._kb.create_item(
query_pattern=pattern.pattern_description,
- query_examples=examples[:5],
+ query_examples=sampled,
skill_ids=top_skills,
- success_count=pattern.raw_trace_count,
+ success_count=len(cluster.success_traces) if cluster else 0,
)
batch_items.append(item)
@@ -197,6 +219,106 @@ class ExperienceBaseBuilder:
)
return created
+ def _merge_similar_patterns(
+ self,
+ patterns: list[DistilledPattern],
+ cluster_by_id: dict[int, ClusteredQuery],
+ ) -> list[DistilledPattern]:
+ if len(patterns) <= 1 or self._pattern_merge_threshold >= 1.0:
+ return list(patterns)
+
+ threshold = float(self._pattern_merge_threshold)
+
+ def skill_bucket_key(p: DistilledPattern) -> frozenset:
+ return frozenset(p.effective_skills)
+
+ buckets: dict[frozenset, list[int]] = defaultdict(list)
+ for i, p in enumerate(patterns):
+ buckets[skill_bucket_key(p)].append(i)
+
+ def success_count(i: int) -> int:
+ c = cluster_by_id.get(patterns[i].cluster_id)
+ return len(c.success_traces) if c else 0
+
+ merged: list[DistilledPattern] = []
+ synthetic_counter = 1
+ for bucket_indices in buckets.values():
+ ordered = sorted(
+ bucket_indices,
+ key=success_count,
+ reverse=True,
+ )
+ if len(ordered) == 1:
+ merged.append(patterns[ordered[0]])
+ continue
+
+ descriptions = [patterns[i].pattern_description for i in ordered]
+ embeddings = self._embedder.embed_batch(descriptions)
+ arr = np.asarray(embeddings, dtype=np.float32)
+ norms = np.linalg.norm(arr, axis=1, keepdims=True)
+ norms[norms == 0] = 1.0
+ unit = arr / norms
+ local_sim = unit @ unit.T # cosine similarity within bucket
+ n = len(ordered)
+ triu_mask = np.triu(np.ones((n, n), dtype=bool), k=1)
+
+ assigned = np.zeros(n, dtype=bool)
+ while True:
+ avail_mask = (~assigned)[:, None] & (~assigned)[None, :] & triu_mask
+ sim_view = np.where(avail_mask, local_sim, -np.inf)
+ if not np.isfinite(sim_view).any() or float(sim_view.max()) < threshold:
+ for pos in np.nonzero(~assigned)[0]:
+ merged.append(patterns[ordered[int(pos)]])
+ break
+
+ flat = int(np.argmax(sim_view))
+ i, j = flat // n, flat % n
+
+ group: list[int] = [i, j]
+ assigned[i] = True
+ assigned[j] = True
+ while True:
+ candidates = np.nonzero(~assigned)[0]
+ if len(candidates) == 0:
+ break
+ sub = local_sim[np.ix_(group, candidates)]
+ weakest = sub.min(axis=0) # min sim vs group, per candidate
+ score = np.where(
+ np.all(sub >= threshold, axis=0), weakest, -np.inf,
+ )
+ if not np.isfinite(score).any():
+ break
+ pick = int(candidates[int(np.argmax(score))])
+ group.append(pick)
+ assigned[pick] = True
+
+ rep = patterns[ordered[group[0]]]
+ pooled: list[TraceRecord] = []
+ for pos in group:
+ cluster = cluster_by_id.get(patterns[ordered[pos]].cluster_id)
+ if cluster:
+ pooled.extend(cluster.success_traces)
+ synthetic_id = -synthetic_counter
+ synthetic_counter += 1
+ cluster_by_id[synthetic_id] = ClusteredQuery(
+ cluster_id=synthetic_id,
+ centroid_query=rep.pattern_description,
+ member_traces=list(pooled),
+ success_traces=list(pooled),
+ failure_traces=[],
+ )
+ merged.append(DistilledPattern(
+ cluster_id=synthetic_id,
+ effective_skills=rep.effective_skills,
+ pattern_description=rep.pattern_description,
+ ))
+
+ LOGGER.info(
+ "TraceIndexBuilder: merged %d patterns (threshold=%.2f, similarity-first greedy, bucketed-by-skill)",
+ len(merged), threshold,
+ )
+ return merged
+
# ------------------------------------------------------------------
# Internal
# ------------------------------------------------------------------
@@ -221,11 +343,11 @@ class ExperienceBaseBuilder:
queries = [r.query for r in records]
embeddings = self._embedder.embed_batch(queries)
- cluster_labels = _faiss_cluster(embeddings, min_cluster_size=1)
+ cluster_labels = _faiss_cluster(embeddings, n_clusters=self._skill_cluster_num,
+ min_cluster_size=self._min_cluster_size)
created = 0
- from collections import defaultdict as _dd
- clusters: dict[int, list[TraceRecord]] = _dd(list)
+ clusters: dict[int, list[TraceRecord]] = defaultdict(list)
noise: list[TraceRecord] = []
local_clusters: dict[int, list[int]] = {}
for i, label in enumerate(cluster_labels):
@@ -274,7 +396,7 @@ class ExperienceBaseBuilder:
examples = [trace.query for trace in cluster.member_traces]
# 先做 embedding 去重
- items = self._kb.search_by_embedding(distilled[0].pattern_description, threshold=0.75)
+ items = self._kb.search_by_embedding(distilled[0].pattern_description, threshold=self._pattern_merge_threshold)
if items:
# 检查是否有相同 skill 组合的 item
for _, existing in items:
@@ -292,9 +414,10 @@ class ExperienceBaseBuilder:
skill_ids: list[str],
) -> ExperienceItem:
"""Helper to create a new experience item."""
+ sample_n = max(0, self._query_examples_count)
item = self._kb.create_item(
query_pattern=pattern,
- query_examples=query_examples[:5],
+ query_examples=query_examples[:sample_n],
skill_ids=skill_ids,
)
self._kb.add(item)
diff --git a/jiuwenswarm/symphony/experience/distiller.py b/jiuwenswarm/symphony/experience/distiller.py
index b8511e9b9c..a0c89e3e46 100644
--- a/jiuwenswarm/symphony/experience/distiller.py
+++ b/jiuwenswarm/symphony/experience/distiller.py
@@ -8,7 +8,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any
from .cluster import ClusteredQuery
-from .models import DistilledPattern, TraceRecord
+from .models import DistilledPattern
LOGGER = logging.getLogger(__name__)
@@ -114,12 +114,11 @@ class TraceDistiller:
return [r for r in results if r is not None]
def _distill_one(self, cluster: ClusteredQuery) -> DistilledPattern | None:
- metrics = self._compute_metrics(cluster.success_traces, cluster.failure_traces)
+ success_traces = cluster.success_traces
+ effective_skills = list(success_traces[0].skills) if success_traces else []
- success_queries = [t.query for t in cluster.success_traces]
- used_skill_names = {
- s for combo in metrics["effective_skills"] for s in combo
- }
+ success_queries = [t.query for t in success_traces]
+ used_skill_names = set(effective_skills)
prompt = self._build_prompt(cluster, success_queries, used_skill_names)
@@ -156,47 +155,10 @@ class TraceDistiller:
return DistilledPattern(
cluster_id=cluster.cluster_id,
+ effective_skills=effective_skills,
pattern_description=pattern_description,
- **metrics,
)
- @staticmethod
- def _compute_metrics(
- success_traces: list[TraceRecord],
- failure_traces: list[TraceRecord],
- ) -> dict[str, Any]:
- effective_skills_map: dict[tuple[str, ...], int] = {}
- for t in success_traces:
- key = tuple(sorted(t.skills))
- effective_skills_map[key] = effective_skills_map.get(key, 0) + 1
- effective_skills = [
- list(k)
- for k, _ in sorted(effective_skills_map.items(), key=lambda x: -x[1])
- ]
-
- ineffective_skills: list[dict[str, str | list[str]]] = []
- seen: set[tuple[str, ...]] = set()
- for t in failure_traces:
- key = tuple(sorted(t.skills))
- if key not in seen:
- seen.add(key)
- ineffective_skills.append(
- {
- "skills": list(key),
- "reason": t.error_type or "unknown",
- }
- )
-
- total = len(success_traces) + len(failure_traces)
- success_rate = len(success_traces) / total if total > 0 else 0.0
-
- return {
- "effective_skills": effective_skills,
- "ineffective_skills": ineffective_skills,
- "success_rate": success_rate,
- "raw_trace_count": total,
- }
-
def _build_prompt(
self,
cluster: ClusteredQuery,
diff --git a/jiuwenswarm/symphony/experience/models.py b/jiuwenswarm/symphony/experience/models.py
index 5f77cf4132..6cc7905a29 100644
--- a/jiuwenswarm/symphony/experience/models.py
+++ b/jiuwenswarm/symphony/experience/models.py
@@ -91,6 +91,10 @@ class ExperienceBankBuildConfig:
max_success_examples: int = 20
pending_flush_threshold: int = 20
min_hits_for_pattern: int = 1
+ skill_cluster_num: int | None = None
+ pattern_merge_threshold: float = 0.9
+ query_examples_count: int = 5
+ cluster_max_examples: int | None = None
@dataclass
@@ -98,10 +102,7 @@ class DistilledPattern:
"""Distilled knowledge pattern from one cluster."""
cluster_id: int
- effective_skills: list[list[str]] = field(default_factory=list)
- ineffective_skills: list[dict[str, str | list[str]]] = field(default_factory=list)
- success_rate: float = 0.0
- raw_trace_count: int = 0
+ effective_skills: list[str] = field(default_factory=list)
pattern_description: str = ""
def to_dict(self) -> dict[str, Any]:
@@ -109,9 +110,6 @@ class DistilledPattern:
return {
"cluster_id": self.cluster_id,
"effective_skills": self.effective_skills,
- "ineffective_skills": self.ineffective_skills,
- "success_rate": self.success_rate,
- "raw_trace_count": self.raw_trace_count,
"pattern_description": self.pattern_description,
}
@@ -121,8 +119,5 @@ class DistilledPattern:
return cls(
cluster_id=d["cluster_id"],
effective_skills=list(d.get("effective_skills", [])),
- ineffective_skills=list(d.get("ineffective_skills", [])),
- success_rate=float(d.get("success_rate", 0.0)),
- raw_trace_count=int(d.get("raw_trace_count", 0)),
pattern_description=str(d.get("pattern_description", "")),
)
\ No newline at end of file
diff --git a/jiuwenswarm/symphony/experience/retriever.py b/jiuwenswarm/symphony/experience/retriever.py
index 9634e7b892..6afd0d9e7f 100644
--- a/jiuwenswarm/symphony/experience/retriever.py
+++ b/jiuwenswarm/symphony/experience/retriever.py
@@ -22,13 +22,15 @@ class ExperienceRetriever:
self._top_k = top_k
def search(self, query: str) -> list[str]:
- """Search the experience KB. Returns skill list on hit, None on miss."""
+ """Search the experience KB."""
results = self._kb.search_by_embedding(
query, top_k=self._top_k, threshold=self._threshold
)
if not results:
return []
- return [skill_id for result in results for skill_id in result[1].skill_ids]
+ return list(dict.fromkeys(
+ skill_id for result in results for skill_id in result[1].skill_ids
+ ))
__all__ = ["ExperienceRetriever"]