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

feat(skill): Experience-based skill distribution enhancement.

chunbs_cbs305534660562
diff --git a/jiuwenswarm/symphony/experience/__init__.py b/jiuwenswarm/symphony/experience/__init__.py
index 8f92247306..5ba54642ec 100644
--- a/jiuwenswarm/symphony/experience/__init__.py
+++ b/jiuwenswarm/symphony/experience/__init__.py
@@ -5,9 +5,11 @@ if TYPE_CHECKING:
from .distiller import TraceDistiller
from .cluster import cluster_traces, ClusteredQuery
from .collector import ExperienceBaseBuilder
+ from .embed import EmbeddingClient
+ from .retriever import ExperienceRetriever
from .evaluator import TraceEvaluator
-from .models import TraceRecord, DistilledPattern
+from .models import TraceRecord, DistilledPattern, ExperienceBankBuildConfig
from .trace import (
list_session_ids,
parse_all_sessions,
@@ -20,6 +22,7 @@ from .trace import (
__all__ = [
"TraceRecord",
"DistilledPattern",
+ "ExperienceBankBuildConfig",
"list_session_ids",
"parse_session",
"parse_all_sessions",
@@ -31,7 +34,9 @@ __all__ = [
"TraceDistiller",
"cluster_traces",
"ClusteredQuery",
- "ExperienceBaseBuilder"
+ "ExperienceBaseBuilder",
+ 'EmbeddingClient',
+ 'ExperienceRetriever'
]
@@ -42,7 +47,9 @@ def __getattr__(name):
"TraceDistiller": ".distiller",
"cluster_traces": ".cluster",
"ClusteredQuery": ".cluster",
- "ExperienceBaseBuilder": ".collector"
+ "ExperienceBaseBuilder": ".collector",
+ "EmbeddingClient": ".embed",
+ "ExperienceRetriever": ".retriever",
}
if name in lazy:
import importlib
diff --git a/jiuwenswarm/symphony/experience/bank.py b/jiuwenswarm/symphony/experience/bank.py
index 104ed8d0bd..dd39453451 100644
--- a/jiuwenswarm/symphony/experience/bank.py
+++ b/jiuwenswarm/symphony/experience/bank.py
@@ -30,7 +30,8 @@ _HASH_CHUNK_SIZE = 8192
class _KnowledgeMeta:
version: int = 1
vector_count: int = 0
- vector_algorithm: str = "IndexFlatIP"
+ vector_algorithm: str = "Flat"
+ vector_dimension: int = 0
vector_sha256: str = ""
scalar_sha256: str = ""
@@ -55,21 +56,25 @@ def _sha256_file(path: Path) -> str:
return h.hexdigest()
-_FAISSENTRIES = {
- "IndexFlatIP": faiss.IndexFlatIP,
- "IndexFlatL2": faiss.IndexFlatL2,
- "IndexIDMap": faiss.IndexIDMap,
-}
-def _build_faiss_index(algorithm: str, dim: int) -> faiss.Index:
- cls = _FAISSENTRIES.get(algorithm)
- if cls is None:
+def _build_faiss_index(algorithm: str, dim: int) -> tuple[faiss.Index, str]:
+ actual_algorithm = algorithm
+ try:
+ index = faiss.index_factory(dim, algorithm, faiss.METRIC_INNER_PRODUCT)
+ except (RuntimeError, ValueError) as exc:
LOGGER.warning(
- "ExperienceBank: unknown FAISS algorithm '%s', falling back to IndexFlatIP", algorithm,
+ "ExperienceBank: index_factory failed for '%s' (dim=%d): %s, falling back to Flat",
+ algorithm, dim, exc,
)
- cls = faiss.IndexFlatIP
- return cls(dim)
+ index = faiss.index_factory(dim, "Flat", faiss.METRIC_INNER_PRODUCT)
+ actual_algorithm = "Flat"
+
+ # IVF-style indices need training before adding vectors
+ if isinstance(index, faiss.IndexIVF):
+ index.nprobe = 10 # reasonable default for search recall
+
+ return index, actual_algorithm
def _write_atomic(source: Path, target: Path) -> None:
@@ -79,9 +84,9 @@ def _write_atomic(source: Path, target: Path) -> None:
try:
_win_retry(lambda: os.replace(str(source), str(target)), retries=5, delay=0.2)
except FileNotFoundError:
- LOGGER.debug("_write_atomic: source file vanished/locked during replace: %s", source)
+ LOGGER.debug("_write_atomic: source=%s, target=%s — file vanished/locked during replace", source, target)
except Exception:
- LOGGER.warning("_write_atomic failed for %s -> %s", source, target, exc_info=True)
+ LOGGER.warning("_write_atomic failed", exc_info=True)
class ExperienceBank:
@@ -105,7 +110,7 @@ class ExperienceBank:
index_dir: str | Path,
embedding_client: EmbeddingClient,
*,
- vector_algorithm: str = "IndexFlatIP",
+ vector_algorithm: str = "Flat",
) -> None:
self._dir = Path(index_dir)
self._embedder = embedding_client
@@ -295,6 +300,15 @@ class ExperienceBank:
meta.vector_count, len(self._items),
)
+ # 4b. Validate vector dimension against manifest
+ if meta.vector_dimension and self._embedding_matrix is not None:
+ actual_dim = self._embedding_matrix.shape[1]
+ if meta.vector_dimension != actual_dim:
+ LOGGER.warning(
+ "ExperienceBank: vector_dimension mismatch: manifest says %d, actual %d",
+ meta.vector_dimension, actual_dim,
+ )
+
# 5. Initialize ID counter from max existing ID
if self._items:
max_id = 0
@@ -347,9 +361,11 @@ class ExperienceBank:
_write_atomic(tmp_emb.with_suffix(".npy"), emb_path)
# 4. Write meta.json (integrity manifest)
+ dim = self._embedding_matrix.shape[1] if self._embedding_matrix is not None else 0
meta = _KnowledgeMeta(
vector_count=len(self._items),
vector_algorithm=self._vector_algorithm,
+ vector_dimension=dim,
vector_sha256=_sha256_file(vector_dir / _FAISS_FILE) if self._faiss_index is not None else "",
scalar_sha256=_sha256_file(scalar_path),
)
@@ -384,7 +400,21 @@ class ExperienceBank:
arr = np.array(embeddings, dtype=np.float32)
dim = arr.shape[1]
- index = _build_faiss_index(self._vector_algorithm, dim)
+ index, actual_algorithm = _build_faiss_index(self._vector_algorithm, dim)
+ self._vector_algorithm = actual_algorithm
+
+ # IVF-style indices require training on the dataset first
+ if isinstance(index, faiss.IndexIVF):
+ if len(arr) >= index.nlist:
+ index.train(arr)
+ else:
+ # Too few vectors for IVF; fall back to Flat
+ LOGGER.info(
+ "ExperienceBank: too few vectors (%d) for IVF nlist=%d, falling back to Flat",
+ len(arr), index.nlist,
+ )
+ index = faiss.index_factory(dim, "Flat", faiss.METRIC_INNER_PRODUCT)
+ self._vector_algorithm = "Flat"
index.add(arr)
self._faiss_index = index
diff --git a/jiuwenswarm/symphony/experience/cluster.py b/jiuwenswarm/symphony/experience/cluster.py
index 9cfc88533c..85d2ff0be4 100644
--- a/jiuwenswarm/symphony/experience/cluster.py
+++ b/jiuwenswarm/symphony/experience/cluster.py
@@ -144,7 +144,7 @@ def _faiss_cluster(
# Auto-determine k: aim for clusters of 3-8 items
if n_clusters is None:
- k = max(2, min(n // 3, n))
+ k = max(2, n // 3)
else:
k = max(2, min(n_clusters, n))
k = min(k, n)
diff --git a/jiuwenswarm/symphony/experience/collector.py b/jiuwenswarm/symphony/experience/collector.py
index c9cb7dd911..41bb113d95 100644
--- a/jiuwenswarm/symphony/experience/collector.py
+++ b/jiuwenswarm/symphony/experience/collector.py
@@ -1,18 +1,17 @@
from __future__ import annotations
-import json
import logging
import threading
import time
from collections import defaultdict
-from pathlib import Path
from typing import Any
+from . import ExperienceBank
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 ExperienceItem, TraceRecord
+from .models import ExperienceBankBuildConfig, ExperienceItem, TraceRecord
LOGGER = logging.getLogger(__name__)
@@ -26,27 +25,28 @@ class ExperienceBaseBuilder:
self,
kb: ExperienceBank,
embedding_client: EmbeddingClient,
- llm_client: Any | None = None,
- llm_model: str = "",
+ llm_client: Any,
+ llm_model: str,
*,
skills_info: list[dict[str, str]] | None = None,
- min_cluster_size: int = 1,
- max_workers: int = 8,
- max_success_examples: int = 20,
- pending_flush_threshold: int = 20,
- min_hits_for_pattern: int = 1,
+ build_config: ExperienceBankBuildConfig | None = None,
) -> None:
self._kb = kb
self._embedder = embedding_client
+ if not llm_client:
+ raise ValueError("ExperienceBaseBuilder requires llm_client for distillation.")
self._llm = llm_client
- self._llm_model = str(llm_model or "").strip()
+ if not llm_model:
+ raise ValueError("ExperienceBaseBuilder requires llm_model for distillation.")
+ self._llm_model = llm_model
self._skills_info = skills_info
- self._min_cluster_size = int(min_cluster_size)
- self._max_workers = int(max_workers)
- self._max_success_examples = int(max_success_examples)
+ self._config = build_config or ExperienceBankBuildConfig()
+ self._min_cluster_size = self._config.min_cluster_size
+ self._max_workers = self._config.max_workers
+ self._max_success_examples = self._config.max_success_examples
self._pending: list[TraceRecord] = []
- self._flush_threshold = int(pending_flush_threshold)
- self._min_hits = int(min_hits_for_pattern)
+ self._flush_threshold = self._config.pending_flush_threshold
+ self._min_hits = self._config.min_hits_for_pattern
self._lock = threading.Lock()
def build(self, traces: list[TraceRecord]) -> int:
@@ -145,22 +145,6 @@ class ExperienceBaseBuilder:
)
return created
- def build_from_file(self, traces_path: str | Path) -> int:
- """Convenience: read a JSON file, parse into ``TraceRecord`` list,
- then call :meth:`build`.
-
- The JSON file should contain a list of trace dicts, or a top-level
- dict with ``"traces"`` or ``"records"`` key.
- """
- data = json.loads(Path(traces_path).read_text(encoding="utf-8"))
- if isinstance(data, dict):
- data = data.get("traces", data.get("records", [data]))
- traces = [TraceRecord.from_dict(d) for d in data]
- LOGGER.info(
- "TraceIndexBuilder: loaded %d traces from %s", len(traces), traces_path
- )
- return self.build(traces)
-
def add(self, trace: TraceRecord) -> None:
"""Record a successful query-skill mapping.
@@ -171,11 +155,6 @@ class ExperienceBaseBuilder:
self._pending.append(trace)
pending_count = len(self._pending)
- LOGGER.debug(
- "ExperienceBaseBuilder: recorded pending record query='%s' skills=%s (total pending=%d)",
- trace.query, trace.skills, pending_count,
- )
-
# Auto-flush if buffer is large enough (non-blocking)
if pending_count >= self._flush_threshold:
with self._lock:
@@ -319,7 +298,6 @@ class ExperienceBaseBuilder:
skill_ids=skill_ids,
)
self._kb.add(item)
- LOGGER.info("ExperienceBaseBuilder: created new item '%s' pattern='%s'", item.id, pattern)
return item
__all__ = ["ExperienceBaseBuilder"]
diff --git a/jiuwenswarm/symphony/experience/distiller.py b/jiuwenswarm/symphony/experience/distiller.py
index f61c1e2742..b8511e9b9c 100644
--- a/jiuwenswarm/symphony/experience/distiller.py
+++ b/jiuwenswarm/symphony/experience/distiller.py
@@ -68,7 +68,7 @@ class TraceDistiller:
def __init__(
self,
- llm_client: Any | None,
+ llm_client: Any,
llm_model: str,
*,
skills_info: list[dict[str, str]] | None = None,
@@ -76,10 +76,9 @@ class TraceDistiller:
max_success_examples: int = 20,
) -> None:
self._llm_model = llm_model
- if llm_client is not None and llm_model:
- self._llm = llm_client
- else:
- self._llm = None
+ if not llm_client or not llm_model:
+ raise ValueError("TraceDistiller requires both llm_client and llm_model.")
+ self._llm = llm_client
self._max_workers = max_workers
self._max_examples = max_success_examples
@@ -124,39 +123,33 @@ class TraceDistiller:
prompt = self._build_prompt(cluster, success_queries, used_skill_names)
- pattern_description = ""
- if self._llm and self._llm_model:
- try:
- response = self._llm.chat.completions.create(
- model=self._llm_model,
- messages=[
- {
- "role": "system",
- "content": (
- "You are an expert at generalizing query patterns. "
- "Output only valid JSON."
- ),
- },
- {"role": "user", "content": prompt},
- ],
- max_tokens=256,
- stream=False,
- )
- content = response.choices[0].message.content
- if content:
- pattern_description = self._parse_response(content, cluster.cluster_id)
- except Exception as exc:
- LOGGER.debug(
- "TraceDistiller: LLM call failed for cluster %d: %s",
- cluster.cluster_id, exc,
- )
- else:
- # No LLM available — use centroid query as the pattern
- pattern_description = cluster.centroid_query
- LOGGER.info(
- "TraceDistiller: no LLM client, using centroid query as pattern for cluster %d",
- cluster.cluster_id,
+ try:
+ response = self._llm.chat.completions.create(
+ model=self._llm_model,
+ messages=[
+ {
+ "role": "system",
+ "content": (
+ "You are an expert at generalizing query patterns. "
+ "Output only valid JSON."
+ ),
+ },
+ {"role": "user", "content": prompt},
+ ],
+ max_tokens=256,
+ stream=False,
+ extra_body={"enable_thinking": False, "thinking": {"type": "disabled"}},
)
+ content = response.choices[0].message.content
+ if not content:
+ raise RuntimeError(
+ f"LLM returned empty content for cluster {cluster.cluster_id}"
+ )
+ pattern_description = self._parse_response(content, cluster.cluster_id)
+ except Exception as exc:
+ raise RuntimeError(
+ f"LLM call failed for cluster {cluster.cluster_id}: {exc}"
+ ) from exc
if not pattern_description:
return None
@@ -194,17 +187,12 @@ class TraceDistiller:
}
)
- avg_success = 0.0
- avg_failure = 0.0
-
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,
- "avg_token_cost_success": avg_success,
- "avg_token_cost_failure": avg_failure,
"success_rate": success_rate,
"raw_trace_count": total,
}
diff --git a/jiuwenswarm/symphony/experience/embed.py b/jiuwenswarm/symphony/experience/embed.py
index 07f6b420a4..2cae001002 100644
--- a/jiuwenswarm/symphony/experience/embed.py
+++ b/jiuwenswarm/symphony/experience/embed.py
@@ -24,9 +24,11 @@ class EmbeddingClient:
model: str = "",
model_name: str = "",
normalize: bool = True,
+ dimension: int | None = None,
) -> None:
self._backend: str = ""
self._normalize = bool(normalize)
+ self._dimension = dimension
self._total_tokens: int = 0
# Path 1: OpenAI-compatible API
@@ -58,6 +60,11 @@ class EmbeddingClient:
"Option 2: install 'sentence-transformers' and provide model_name."
)
+ @property
+ def dimension(self) -> int | None:
+ """Return the configured embedding vector dimension, or None if unset."""
+ return self._dimension
+
def reset_token_counter(self) -> int:
"""Reset and return the accumulated token counter."""
prev = self._total_tokens
@@ -84,7 +91,13 @@ class EmbeddingClient:
# -- private --
def _embed_api(self, text: str) -> list[float]:
- resp = self._api_client.embeddings.create(input=text, model=self._api_model)
+ params: dict[str, Any] = {
+ "input": text,
+ "model": self._api_model,
+ }
+ if self._dimension is not None:
+ params["dimensions"] = self._dimension
+ resp = self._api_client.embeddings.create(**params)
vec = resp.data[0].embedding
usage = getattr(resp, "usage", None)
if usage is not None:
diff --git a/jiuwenswarm/symphony/experience/evaluator.py b/jiuwenswarm/symphony/experience/evaluator.py
index b2126d03dd..3f44ce14d3 100644
--- a/jiuwenswarm/symphony/experience/evaluator.py
+++ b/jiuwenswarm/symphony/experience/evaluator.py
@@ -204,6 +204,7 @@ class TraceEvaluator:
],
max_tokens=256,
stream=False,
+ extra_body={"enable_thinking": False, "thinking": {"type": "disabled"}},
)
content = response.choices[0].message.content
if content:
diff --git a/jiuwenswarm/symphony/experience/models.py b/jiuwenswarm/symphony/experience/models.py
index c59cdb731e..5f77cf4132 100644
--- a/jiuwenswarm/symphony/experience/models.py
+++ b/jiuwenswarm/symphony/experience/models.py
@@ -82,6 +82,17 @@ class TraceRecord:
)
+@dataclass
+class ExperienceBankBuildConfig:
+ """Configuration for ExperienceBaseBuilder pipeline."""
+
+ min_cluster_size: int = 1
+ max_workers: int = 8
+ max_success_examples: int = 20
+ pending_flush_threshold: int = 20
+ min_hits_for_pattern: int = 1
+
+
@dataclass
class DistilledPattern:
"""Distilled knowledge pattern from one cluster."""
@@ -90,8 +101,6 @@ class DistilledPattern:
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
- avg_token_cost_success: float = 0.0
- avg_token_cost_failure: float = 0.0
raw_trace_count: int = 0
pattern_description: str = ""
@@ -102,8 +111,6 @@ class DistilledPattern:
"effective_skills": self.effective_skills,
"ineffective_skills": self.ineffective_skills,
"success_rate": self.success_rate,
- "avg_token_cost_success": self.avg_token_cost_success,
- "avg_token_cost_failure": self.avg_token_cost_failure,
"raw_trace_count": self.raw_trace_count,
"pattern_description": self.pattern_description,
}
@@ -116,8 +123,6 @@ class DistilledPattern:
effective_skills=list(d.get("effective_skills", [])),
ineffective_skills=list(d.get("ineffective_skills", [])),
success_rate=float(d.get("success_rate", 0.0)),
- avg_token_cost_success=float(d.get("avg_token_cost_success", 0.0)),
- avg_token_cost_failure=float(d.get("avg_token_cost_failure", 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
new file mode 100644
index 0000000000..9634e7b892
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/retriever.py
@@ -0,0 +1,34 @@
+from __future__ import annotations
+
+from .bank import ExperienceBank
+
+
+class ExperienceRetriever:
+ """Fast-path retriever that queries the experience knowledge base.
+
+ On hit: returns skill_ids from the matched experience item.
+ On miss: returns None so the caller falls through to tree retrieval.
+ """
+
+ def __init__(
+ self,
+ kb: ExperienceBank,
+ *,
+ threshold: float = 0.80,
+ top_k: int = 1,
+ ) -> None:
+ self._kb = kb
+ self._threshold = threshold
+ self._top_k = top_k
+
+ def search(self, query: str) -> list[str]:
+ """Search the experience KB. Returns skill list on hit, None on miss."""
+ 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]
+
+
+__all__ = ["ExperienceRetriever"]
diff --git a/jiuwenswarm/symphony/experience/trace/store.py b/jiuwenswarm/symphony/experience/trace/store.py
index fc75468871..0ac58822ce 100644
--- a/jiuwenswarm/symphony/experience/trace/store.py
+++ b/jiuwenswarm/symphony/experience/trace/store.py
@@ -120,7 +120,6 @@ def clear_store() -> None:
for path in [store / "records.jsonl", store / "processed_index.json"]:
if path.exists():
path.unlink()
- LOGGER.info("Removed %s", path)
LOGGER.info("clear_store: store cleared")