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 dispatch experience): trace collect, correctness evaluate, embed and store

Haowei_Du3c215fa65a75
diff --git a/jiuwenswarm/symphony/experience/__init__.py b/jiuwenswarm/symphony/experience/__init__.py
new file mode 100644
index 0000000000..8f92247306
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/__init__.py
@@ -0,0 +1,51 @@
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .bank import ExperienceBank
+ from .distiller import TraceDistiller
+ from .cluster import cluster_traces, ClusteredQuery
+ from .collector import ExperienceBaseBuilder
+
+from .evaluator import TraceEvaluator
+from .models import TraceRecord, DistilledPattern
+from .trace import (
+ list_session_ids,
+ parse_all_sessions,
+ parse_session,
+ parse_and_store,
+ load_all_records,
+ clear_store,
+)
+
+__all__ = [
+ "TraceRecord",
+ "DistilledPattern",
+ "list_session_ids",
+ "parse_session",
+ "parse_all_sessions",
+ "TraceEvaluator",
+ "parse_and_store",
+ "load_all_records",
+ "clear_store",
+ "ExperienceBank",
+ "TraceDistiller",
+ "cluster_traces",
+ "ClusteredQuery",
+ "ExperienceBaseBuilder"
+]
+
+
+def __getattr__(name):
+ """Lazy import for modules that depend on optional packages (faiss, etc.)."""
+ lazy = {
+ "ExperienceBank": ".bank",
+ "TraceDistiller": ".distiller",
+ "cluster_traces": ".cluster",
+ "ClusteredQuery": ".cluster",
+ "ExperienceBaseBuilder": ".collector"
+ }
+ if name in lazy:
+ import importlib
+ mod = importlib.import_module(lazy[name], __package__)
+ return getattr(mod, name)
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/jiuwenswarm/symphony/experience/bank.py b/jiuwenswarm/symphony/experience/bank.py
new file mode 100644
index 0000000000..104ed8d0bd
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/bank.py
@@ -0,0 +1,429 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import threading
+import time
+from dataclasses import dataclass
+from pathlib import Path
+
+import faiss
+import numpy as np
+
+from .embed import EmbeddingClient
+from .models import ExperienceItem
+
+LOGGER = logging.getLogger(__name__)
+
+_META_FILE = "meta.json"
+_SCALAR_DIR = "scalar"
+_SCALAR_FILE = "metadata.jsonl"
+_VECTOR_DIR = "vector"
+_FAISS_FILE = "faiss_index.bin"
+_EMBED_FILE = "embeddings.npy"
+_HASH_CHUNK_SIZE = 8192
+
+
+@dataclass
+class _KnowledgeMeta:
+ version: int = 1
+ vector_count: int = 0
+ vector_algorithm: str = "IndexFlatIP"
+ vector_sha256: str = ""
+ scalar_sha256: str = ""
+
+
+def _win_retry(func, retries: int = 3, delay: float = 0.1):
+ """Retry a callable on Windows file-lock errors."""
+ for i in range(retries):
+ try:
+ return func()
+ except OSError:
+ if i == retries - 1:
+ raise
+ time.sleep(delay)
+ return None # Unreachable, satisfies static analysis
+
+
+def _sha256_file(path: Path) -> str:
+ h = hashlib.sha256()
+ with _win_retry(lambda: open(path, "rb")) as f:
+ for chunk in iter(lambda: f.read(_HASH_CHUNK_SIZE), b""):
+ h.update(chunk)
+ 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:
+ LOGGER.warning(
+ "ExperienceBank: unknown FAISS algorithm '%s', falling back to IndexFlatIP", algorithm,
+ )
+ cls = faiss.IndexFlatIP
+ return cls(dim)
+
+
+def _write_atomic(source: Path, target: Path) -> None:
+ """Atomically replace *target* with *source* (Windows-safe)."""
+ if not source.exists():
+ return
+ 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)
+ except Exception:
+ LOGGER.warning("_write_atomic failed for %s -> %s", source, target, exc_info=True)
+
+
+class ExperienceBank:
+ """Persistent knowledge base for experience items.
+
+ Storage layout (directory-based)::
+
+ experience_kb/
+ ├── meta.json # integrity manifest
+ ├── scalar/
+ │ └── metadata.jsonl # item metadata (no embeddings)
+ └── vector/
+ ├── faiss_index.bin # FAISS index
+ └── embeddings.npy # embedding matrix
+
+ All items are loaded into memory; FAISS provides fast search.
+ """
+
+ def __init__(
+ self,
+ index_dir: str | Path,
+ embedding_client: EmbeddingClient,
+ *,
+ vector_algorithm: str = "IndexFlatIP",
+ ) -> None:
+ self._dir = Path(index_dir)
+ self._embedder = embedding_client
+ self._vector_algorithm = vector_algorithm
+ self._items: list[ExperienceItem] = []
+ self._id_index: dict[str, ExperienceItem] = {}
+ self._skills: set[frozenset] = set()
+ self._embedding_matrix: np.ndarray | None = None
+ self._faiss_index: faiss.Index | None = None
+ self._write_lock = threading.Lock()
+ self._next_id_counter = 0
+ self._load()
+
+ # ------------------------------------------------------------------
+ # CRUD
+ # ------------------------------------------------------------------
+
+ @property
+ def items(self) -> list[ExperienceItem]:
+ return list(self._items)
+
+ @property
+ def count(self) -> int:
+ return len(self._items)
+
+ def exist(self, skills: list[str]) -> bool:
+ return frozenset(skills) in self._skills
+
+ def add(self, item: ExperienceItem) -> None:
+ """Add a new experience item to the KB and persist."""
+ with self._write_lock:
+ self._items.append(item)
+ self._id_index[item.id] = item
+ self._skills.add(frozenset(item.skill_ids))
+ self._rebuild_index()
+ self.persist()
+
+ def add_batch(self, items: list[ExperienceItem]) -> None:
+ """Add multiple items at once, rebuilding index and persisting only once."""
+ if not items:
+ return
+ with self._write_lock:
+ for item in items:
+ self._items.append(item)
+ self._id_index[item.id] = item
+ self._skills.add(frozenset(item.skill_ids))
+ self._rebuild_index()
+ self.persist()
+
+ def remove(self, item_id: str) -> bool:
+ """Remove an item by id. Returns True if found and removed."""
+ with self._write_lock:
+ item = self._id_index.pop(item_id, None)
+ if item is None:
+ return False
+ self._items = [i for i in self._items if i.id != item_id]
+ self._skills.discard(frozenset(item.skill_ids))
+ self._rebuild_index()
+ self.persist()
+ return True
+
+ # ------------------------------------------------------------------
+ # FAISS search
+ # ------------------------------------------------------------------
+
+ def search_by_embedding(
+ self,
+ query: str,
+ top_k: int = 1,
+ threshold: float = 0.80,
+ ) -> list[tuple[float, ExperienceItem]]:
+ """Search the KB by embedding similarity using FAISS.
+
+ Returns a list of (similarity_score, item) sorted descending.
+ Items below threshold are excluded.
+ """
+ if self._faiss_index is None or not self._items:
+ return []
+
+ query_emb = self._embedder.embed(query)
+ query_vec = np.asarray([query_emb], dtype=np.float32)
+
+ k = min(top_k, len(self._items))
+ distances, indices = self._faiss_index.search(query_vec, k)
+
+ results = []
+ for i in range(k):
+ if i >= len(indices[0]):
+ break
+ idx = int(indices[0][i])
+ score = float(distances[0][i])
+ if score >= threshold and idx < len(self._items):
+ results.append((score, self._items[idx]))
+
+ return results
+
+ def search_with_skill_ids(
+ self,
+ query: str,
+ top_k: int = 1,
+ threshold: float = 0.80,
+ ) -> list[str]:
+ """Convenience: return just the skill_ids of the best match."""
+ results = self.search_by_embedding(query, top_k=top_k, threshold=threshold)
+ skills: list[str] = []
+ for _sim, item in results:
+ for sid in item.skill_ids:
+ if sid not in skills:
+ skills.append(sid)
+ return skills
+
+ # ------------------------------------------------------------------
+ # Persistence
+ # ------------------------------------------------------------------
+
+ def _load(self) -> None:
+ if not self._dir.exists():
+ LOGGER.info("ExperienceBank: index directory does not exist, starting empty")
+ return
+
+ meta_path = self._dir / _META_FILE
+ scalar_path = self._dir / _SCALAR_DIR / _SCALAR_FILE
+ faiss_path = self._dir / _VECTOR_DIR / _FAISS_FILE
+ emb_path = self._dir / _VECTOR_DIR / _EMBED_FILE
+
+ if not meta_path.exists():
+ LOGGER.error("ExperienceBank: integrity manifest (meta.json) is missing, starting empty")
+ return
+
+ if not scalar_path.exists():
+ LOGGER.error("ExperienceBank: scalar metadata file does not exist, starting empty")
+ return
+
+ # --- integrity check ---
+ try:
+ meta_data = json.loads(meta_path.read_text(encoding="utf-8"))
+ meta = _KnowledgeMeta(**meta_data)
+
+ scalar_actual = _sha256_file(scalar_path)
+ if meta.scalar_sha256 and scalar_actual != meta.scalar_sha256:
+ LOGGER.warning(
+ "ExperienceBank: scalar integrity check failed, loading anyway (debug mode)"
+ )
+
+ if faiss_path.exists():
+ faiss_actual = _sha256_file(faiss_path)
+ if meta.vector_sha256 and faiss_actual != meta.vector_sha256:
+ LOGGER.warning(
+ "ExperienceBank: vector integrity check failed, loading anyway (debug mode)"
+ )
+ except Exception as exc:
+ LOGGER.error("ExperienceBank: failed to parse manifest, skipping check")
+
+ try:
+ # 1. Load scalar metadata
+ with open(scalar_path, "r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ data = json.loads(line)
+ item = ExperienceItem.from_dict(data)
+ self._items.append(item)
+ self._id_index[item.id] = item
+ self._skills.add(frozenset(item.skill_ids))
+
+ # 2. Load embeddings matrix and re-hydrate in-memory items
+ if emb_path.exists():
+ self._embedding_matrix = np.load(str(emb_path))
+ # Re-normalize to ensure IndexFlatIP inner product = cosine similarity
+ if self._embedding_matrix is not None and len(self._embedding_matrix) > 0:
+ norms = np.linalg.norm(self._embedding_matrix, axis=1, keepdims=True)
+ norms[norms == 0] = 1.0
+ self._embedding_matrix = self._embedding_matrix / norms
+ for i, item in enumerate(self._items):
+ if i < len(self._embedding_matrix):
+ item.embedding = self._embedding_matrix[i].tolist()
+
+ # 3. Load FAISS index
+ if faiss_path.exists():
+ self._faiss_index = faiss.read_index(str(faiss_path))
+
+ # 4. Validate vector count against manifest
+ if meta.vector_count and meta.vector_count != len(self._items):
+ LOGGER.warning(
+ "ExperienceBank: vector_count mismatch: manifest says %d, loaded %d",
+ meta.vector_count, len(self._items),
+ )
+
+ # 5. Initialize ID counter from max existing ID
+ if self._items:
+ max_id = 0
+ for item in self._items:
+ if item.id.startswith("exp_"):
+ try:
+ num = int(item.id.split("_")[1])
+ max_id = max(max_id, num)
+ except (IndexError, ValueError):
+ pass
+ self._next_id_counter = max_id + 1
+
+ LOGGER.info("ExperienceBank: loaded %d items", len(self._items))
+ except Exception as exc:
+ LOGGER.error("ExperienceBank: failed to load data: %s", exc)
+
+ def persist(self) -> None:
+ """Persist to index_dir with integrity manifest."""
+ # Ensure root directory exists first
+ self._dir.mkdir(parents=True, exist_ok=True)
+
+ scalar_dir = self._dir / _SCALAR_DIR
+ scalar_path = scalar_dir / _SCALAR_FILE
+ vector_dir = self._dir / _VECTOR_DIR
+
+ scalar_dir.mkdir(parents=True, exist_ok=True)
+ vector_dir.mkdir(parents=True, exist_ok=True)
+
+ # 1. Write scalar/metadata.jsonl
+ tmp_scalar = scalar_dir / (_SCALAR_FILE + ".tmp")
+ with open(tmp_scalar, "w", encoding="utf-8") as f:
+ for item in self._items:
+ f.write(json.dumps(item.to_dict(), ensure_ascii=False) + "\n")
+ _write_atomic(tmp_scalar, scalar_path)
+
+ # 2. Write vector/faiss_index.bin
+ if self._faiss_index is not None:
+ faiss_path = vector_dir / _FAISS_FILE
+ tmp_faiss = vector_dir / "faiss_tmp"
+ faiss.write_index(self._faiss_index, str(tmp_faiss))
+ _write_atomic(tmp_faiss, faiss_path)
+
+ # 3. Write vector/embeddings.npy
+ # np.save appends ".npy" automatically, so we write to "embed_tmp"
+ # which produces "embed_tmp.npy", then rename to "embeddings.npy".
+ if self._embedding_matrix is not None:
+ emb_path = vector_dir / _EMBED_FILE
+ tmp_emb = vector_dir / "embed_tmp"
+ np.save(str(tmp_emb), self._embedding_matrix)
+ _write_atomic(tmp_emb.with_suffix(".npy"), emb_path)
+
+ # 4. Write meta.json (integrity manifest)
+ meta = _KnowledgeMeta(
+ vector_count=len(self._items),
+ vector_algorithm=self._vector_algorithm,
+ vector_sha256=_sha256_file(vector_dir / _FAISS_FILE) if self._faiss_index is not None else "",
+ scalar_sha256=_sha256_file(scalar_path),
+ )
+ tmp_meta = self._dir / (_META_FILE + ".tmp")
+ tmp_meta.write_text(
+ json.dumps(meta.__dict__, ensure_ascii=False, indent=2) + "\n",
+ encoding="utf-8",
+ )
+ _write_atomic(tmp_meta, self._dir / _META_FILE)
+
+ # ------------------------------------------------------------------
+ # Index management
+ # ------------------------------------------------------------------
+
+ def _rebuild_index(self) -> None:
+ """Rebuild FAISS index and embedding matrix from current _items."""
+ if not self._items:
+ self._faiss_index = None
+ self._embedding_matrix = None
+ return
+
+ embeddings = []
+ for item in self._items:
+ if item.embedding:
+ embeddings.append(item.embedding)
+
+ if not embeddings:
+ self._faiss_index = None
+ self._embedding_matrix = None
+ return
+
+ arr = np.array(embeddings, dtype=np.float32)
+ dim = arr.shape[1]
+
+ index = _build_faiss_index(self._vector_algorithm, dim)
+ index.add(arr)
+
+ self._faiss_index = index
+ self._embedding_matrix = arr
+
+ # ------------------------------------------------------------------
+ # Helpers
+ # ------------------------------------------------------------------
+
+ def generate_id(self) -> str:
+ cid = self._next_id_counter
+ self._next_id_counter += 1
+ return f"exp_{cid:04d}"
+
+ def create_item(
+ self,
+ query_pattern: str,
+ query_examples: list[str],
+ skill_ids: list[str],
+ success_count: int = 1,
+ ) -> ExperienceItem:
+ """Create an ExperienceItem with auto-generated embedding and id."""
+ text_for_embedding = query_pattern + "\n" + "\n".join(query_examples)
+ embedding = self._embedder.embed(text_for_embedding)
+
+ return ExperienceItem(
+ id=self.generate_id(),
+ query_pattern=query_pattern,
+ query_examples=query_examples,
+ skill_ids=skill_ids,
+ success_count=success_count,
+ embedding=embedding,
+ created_at=_now(),
+ last_hit_at=_now(),
+ )
+
+
+def _now() -> float:
+ return time.time()
+
+
+__all__ = ["ExperienceBank"]
diff --git a/jiuwenswarm/symphony/experience/cluster.py b/jiuwenswarm/symphony/experience/cluster.py
index 4c1e742e3c..9cfc88533c 100644
--- a/jiuwenswarm/symphony/experience/cluster.py
+++ b/jiuwenswarm/symphony/experience/cluster.py
@@ -141,9 +141,6 @@ def _faiss_cluster(
# Normalize vectors for inner-product = cosine similarity
arr = np.array(embeddings, dtype=np.float32)
- norms = np.linalg.norm(arr, axis=1, keepdims=True)
- norms[norms == 0] = 1.0
- arr = arr / norms
# Auto-determine k: aim for clusters of 3-8 items
if n_clusters is None:
diff --git a/jiuwenswarm/symphony/experience/collector.py b/jiuwenswarm/symphony/experience/collector.py
index 0b60c7c6fc..c9cb7dd911 100644
--- a/jiuwenswarm/symphony/experience/collector.py
+++ b/jiuwenswarm/symphony/experience/collector.py
@@ -1,2 +1,325 @@
+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 .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
+
+LOGGER = logging.getLogger(__name__)
+
+
class ExperienceBaseBuilder:
- pass
\ No newline at end of file
+ """Build an ``ExperienceBank`` index from parsed traces via
+ cluster → distill → persist pipeline.
+ """
+
+ def __init__(
+ self,
+ kb: ExperienceBank,
+ embedding_client: EmbeddingClient,
+ llm_client: Any | None = None,
+ 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,
+ ) -> None:
+ self._kb = kb
+ self._embedder = embedding_client
+ self._llm = llm_client
+ self._llm_model = str(llm_model or "").strip()
+ 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._pending: list[TraceRecord] = []
+ self._flush_threshold = int(pending_flush_threshold)
+ self._min_hits = int(min_hits_for_pattern)
+ self._lock = threading.Lock()
+
+ def build(self, traces: list[TraceRecord]) -> int:
+ """Build the experience KB from a list of parsed ``TraceRecord``.
+
+ Pipeline stages:
+ 1. **Cluster** — group by skill set, then semantic cluster via FAISS
+ 2. **Distill** — LLM distills each cluster into a generalized pattern
+ 3. **Write** — write distilled patterns into ``ExperienceBank``
+
+ Returns the number of experience items created.
+
+ Raises:
+ ValueError: if the target KB already contains entries (full
+ rebuild only — use a fresh directory to avoid accidental data loss).
+ """
+ if self._kb.count > 0:
+ LOGGER.error(
+ "ExperienceBaseBuilder: refusing to build — "
+ "target KB directory is not empty (existing %d entries). "
+ "This is a full-build operation; use a fresh directory to avoid overwriting data.",
+ self._kb.count,
+ )
+ raise ValueError(
+ f"KB directory is not empty: {self._kb.count} entries exist. "
+ f"ExperienceBaseBuilder performs a full build and will overwrite existing data. "
+ f"Use a fresh directory or clear the KB first."
+ )
+
+ t0 = time.monotonic()
+
+ if not traces:
+ LOGGER.warning("TraceIndexBuilder: no traces provided, skipping")
+ return 0
+
+ # --- Cluster ---
+ t1 = time.monotonic()
+ clusters = cluster_traces(traces, self._embedder, self._min_cluster_size)
+ cluster_elapsed = time.monotonic() - t1
+ LOGGER.info(
+ "TraceIndexBuilder: clustering done: %d clusters in %.2fs",
+ len(clusters), cluster_elapsed,
+ )
+
+ if not clusters:
+ LOGGER.warning("TraceIndexBuilder: no clusters formed, skipping")
+ return 0
+
+ # --- Distill ---
+ t2 = time.monotonic()
+ distiller = TraceDistiller(
+ self._llm,
+ self._llm_model,
+ skills_info=self._skills_info,
+ max_workers=self._max_workers,
+ max_success_examples=self._max_success_examples,
+ )
+ distilled = distiller.run(clusters)
+ distill_elapsed = time.monotonic() - t2
+ LOGGER.info(
+ "TraceIndexBuilder: distillation done: %d patterns in %.2fs",
+ len(distilled), distill_elapsed,
+ )
+
+ # --- 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 []
+ cluster = cluster_by_id.get(pattern.cluster_id)
+ examples = [trace.query for trace in cluster.success_traces] if cluster else [pattern.pattern_description]
+ item = self._kb.create_item(
+ query_pattern=pattern.pattern_description,
+ query_examples=examples[:5],
+ skill_ids=top_skills,
+ success_count=pattern.raw_trace_count,
+ )
+ batch_items.append(item)
+
+ self._kb.add_batch(batch_items)
+ created = len(batch_items)
+ build_index_elapsed = time.monotonic() - t3
+ total_elapsed = time.monotonic() - t0
+ LOGGER.info(
+ "TraceIndexBuilder: build index done: %d entries in %.2fs",
+ created, build_index_elapsed,
+ )
+ LOGGER.info(
+ "TraceIndexBuilder: pipeline total: %.2fs, created %d entries",
+ total_elapsed, created,
+ )
+ 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.
+
+ This adds to the pending buffer. Call flush() to cluster and persist.
+ """
+ with self._lock:
+ 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:
+ snapshot = list(self._pending)
+ self._pending.clear()
+ # Flush outside the lock to avoid blocking add() during LLM calls
+ self._flush_snapshot(snapshot)
+
+ def flush(self) -> int:
+ """Cluster pending records and merge into the KB.
+
+ Returns the number of new experience items created.
+ Blocks until complete — use for graceful shutdown only.
+ """
+ with self._lock:
+ if not self._pending:
+ return 0
+ pending = list(self._pending)
+ self._pending.clear()
+
+ return self._flush_snapshot(pending, force=True)
+
+ def _flush_snapshot(self, pending: list[TraceRecord], force: bool = False) -> int:
+ """Flush a snapshot of pending records. Safe to call from any thread."""
+ if not pending:
+ return 0
+
+ # Step 1: group by skill_ids to reduce noise first
+ by_skill = defaultdict(list)
+ for r in pending:
+ by_skill[tuple(sorted(r.skills))].append(r)
+
+ created = 0
+ for skill_key, records in by_skill.items():
+ created += self._cluster_and_merge(records, list(skill_key), force=force)
+
+ LOGGER.info(
+ "ExperienceBaseBuilder: flushed %d pending records, created %d experience items",
+ len(pending), created,
+ )
+ return created
+
+ # ------------------------------------------------------------------
+ # Internal
+ # ------------------------------------------------------------------
+
+ def _cluster_and_merge(
+ self,
+ records: list[TraceRecord],
+ skill_ids: list[str],
+ force: bool = False,
+ ) -> int:
+ """Embed records, cluster by semantic similarity, name each cluster,
+ and write to KB.
+
+ Returns number of items created.
+ """
+ if len(records) < self._min_hits and not force:
+ # Too few records — put back into pending for later
+ self._pending.extend(records)
+ return 0
+
+ # Cluster by embedding
+ queries = [r.query for r in records]
+ embeddings = self._embedder.embed_batch(queries)
+
+ cluster_labels = _faiss_cluster(embeddings, min_cluster_size=1)
+
+ created = 0
+ from collections import defaultdict as _dd
+ clusters: dict[int, list[TraceRecord]] = _dd(list)
+ noise: list[TraceRecord] = []
+ local_clusters: dict[int, list[int]] = {}
+ for i, label in enumerate(cluster_labels):
+ if label >= 0:
+ clusters[label].append(records[i])
+ local_clusters.setdefault(label, []).append(i)
+ else:
+ noise.append(records[i])
+
+ # Put noise back into pending (only if not forcing)
+ if not force:
+ self._pending.extend(noise)
+
+ # Name each cluster and write to KB
+ cluster_id_offset = 0
+ for label, cluster_records in clusters.items():
+ if len(cluster_records) < self._min_hits and not force:
+ self._pending.extend(cluster_records)
+ continue
+ cid = self._kb.count + cluster_id_offset
+ cluster_query = populate_cluster(cid, embeddings, local_clusters[label], cluster_records)
+ item = self._try_merge_into_existing(cluster_query, skill_ids)
+ if item:
+ created += 1
+ cluster_id_offset += 1
+ return created
+
+ def _try_merge_into_existing(
+ self,
+ cluster: ClusteredQuery,
+ skill_ids: list[str],
+ ) -> ExperienceItem | None:
+ """Check if an experience with similar pattern and same skills already exists.
+ If yes, skip (deduplication). If no, create a new item.
+ """
+ distiller = TraceDistiller(
+ self._llm,
+ self._llm_model,
+ skills_info=self._skills_info,
+ max_workers=self._max_workers,
+ max_success_examples=self._max_success_examples,
+ )
+ distilled = distiller.run([cluster])
+ if not distilled:
+ return None
+ examples = [trace.query for trace in cluster.member_traces]
+
+ # 先做 embedding 去重
+ items = self._kb.search_by_embedding(distilled[0].pattern_description, threshold=0.75)
+ if items:
+ # 检查是否有相同 skill 组合的 item
+ for _, existing in items:
+ if set(existing.skill_ids) == set(skill_ids):
+ return None # 完全重复,跳过
+
+ return self._create_new_item(distilled[0].pattern_description, examples, skill_ids)
+
+
+
+ def _create_new_item(
+ self,
+ pattern: str,
+ query_examples: list[str],
+ skill_ids: list[str],
+ ) -> ExperienceItem:
+ """Helper to create a new experience item."""
+ item = self._kb.create_item(
+ query_pattern=pattern,
+ query_examples=query_examples[:5],
+ 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/embed.py b/jiuwenswarm/symphony/experience/embed.py
index e227dd1fcd..07f6b420a4 100644
--- a/jiuwenswarm/symphony/experience/embed.py
+++ b/jiuwenswarm/symphony/experience/embed.py
@@ -7,4 +7,102 @@ LOGGER = logging.getLogger(__name__)
class EmbeddingClient:
- pass
\ No newline at end of file
+ """Minimal embedding client wrapping any OpenAI-compatible embeddings endpoint.
+
+ Supports two backends:
+ 1. OpenAI-compatible API (base_url + api_key) — calls /v1/embeddings
+ 2. Local sentence-transformers model (model_name) — runs locally
+
+ Pass exactly one of (base_url, api_key) or model_name.
+ """
+
+ def __init__(
+ self,
+ *,
+ base_url: str | None = None,
+ api_key: str = "",
+ model: str = "",
+ model_name: str = "",
+ normalize: bool = True,
+ ) -> None:
+ self._backend: str = ""
+ self._normalize = bool(normalize)
+ self._total_tokens: int = 0
+
+ # Path 1: OpenAI-compatible API
+ if base_url:
+ try:
+ from openai import OpenAI
+ self._api_client = OpenAI(base_url=base_url, api_key=api_key or "dummy")
+ self._api_model = str(model or "text-embedding-3-small")
+ self._backend = "openai_api"
+ LOGGER.info("EmbeddingClient: using OpenAI-compatible API, model=%s", self._api_model)
+ return
+ except ImportError:
+ pass
+
+ # Path 2: Local sentence-transformers
+ if model_name:
+ try:
+ from sentence_transformers import SentenceTransformer
+ self._st_model = SentenceTransformer(model_name)
+ self._backend = "sentence_transformers"
+ LOGGER.info("EmbeddingClient: using local sentence-transformers, model=%s", model_name)
+ return
+ except ImportError:
+ pass
+
+ raise RuntimeError(
+ "EmbeddingClient: could not initialize any embedding backend.\n"
+ "Option 1: install 'openai' and provide base_url.\n"
+ "Option 2: install 'sentence-transformers' and provide model_name."
+ )
+
+ def reset_token_counter(self) -> int:
+ """Reset and return the accumulated token counter."""
+ prev = self._total_tokens
+ self._total_tokens = 0
+ return prev
+
+ def embed(self, text: str) -> list[float]:
+ """Return a normalized embedding vector for the given text."""
+ if self._backend == "openai_api":
+ return self._embed_api(text)
+ if self._backend == "sentence_transformers":
+ return self._embed_local(text)
+ raise RuntimeError("No embedding backend initialized")
+
+ def embed_batch(self, texts: list[str]) -> list[list[float]]:
+ """Return embeddings for multiple texts."""
+ if self._backend == "openai_api":
+ return [self._embed_api(t) for t in texts]
+ if self._backend == "sentence_transformers":
+ vecs = self._st_model.encode(texts, normalize_embeddings=self._normalize, show_progress_bar=False)
+ return vecs.tolist()
+ raise RuntimeError("No embedding backend initialized")
+
+ # -- private --
+
+ def _embed_api(self, text: str) -> list[float]:
+ resp = self._api_client.embeddings.create(input=text, model=self._api_model)
+ vec = resp.data[0].embedding
+ usage = getattr(resp, "usage", None)
+ if usage is not None:
+ self._total_tokens += getattr(usage, "total_tokens", 0) or 0
+ if self._normalize:
+ vec = _l2_normalize(vec)
+ return vec
+
+ def _embed_local(self, text: str) -> list[float]:
+ vec = self._st_model.encode(text, normalize_embeddings=self._normalize).tolist()
+ return vec
+
+
+def _l2_normalize(vec: list[float]) -> list[float]:
+ norm = sum(x * x for x in vec) ** 0.5
+ if norm == 0:
+ return vec
+ return [x / norm for x in vec]
+
+
+__all__ = ["EmbeddingClient"]
diff --git a/jiuwenswarm/symphony/experience/evaluator.py b/jiuwenswarm/symphony/experience/evaluator.py
index 48416adbf0..b2126d03dd 100644
--- a/jiuwenswarm/symphony/experience/evaluator.py
+++ b/jiuwenswarm/symphony/experience/evaluator.py
@@ -1,4 +1,4 @@
-"""LLM-based trace processor: judge whether the skills used in a trace were correctly selected."""
+"""LLM-based trace evaluator: judge whether the skills used in a trace were correctly selected."""
from __future__ import annotations
@@ -10,6 +10,115 @@ from .models import TraceRecord
LOGGER = logging.getLogger(__name__)
+_SKILL_CORRECTNESS_PROMPT = """\
+You are a judge that evaluates whether the skills used in a conversation were correctly selected for the user's task.
+
+User query: {query}
+Assistant result: {result}
+
+Determine if the skills used were appropriate for this task. Output ONLY valid JSON with this schema:
+{{"success": true/false, "error_type": "<type or null>", "error_detail": "<reason or null>"}}
+
+A skill selection is "correct" (success=true) when the chosen skills directly address the user's need, their capabilities match what the task requires, and there isn't a clearly better alternative skill available.
+
+A skill selection is "incorrect" (success=false) when:
+- "wrong_skill": The skill doesn't match the task requirements or a different skill would have been much more appropriate.
+- "skill_error": The skill was the right choice but encountered an execution error (tool failure, exception, etc).
+- "incomplete": The skill started but did not finish the task.
+- "refusal": The skill refused to perform the task.
+- "empty": The skill returned an empty or meaningless result.
+
+For incorrect selections, provide a brief error_detail explaining why the skill choice was wrong or what went wrong.
+"""
+
+_SKILL_CORRECTNESS_PROMPT_ENHANCED = """\
+You are a judge that evaluates whether the skills used in a conversation were correctly selected for the user's task, based on the full interaction process.
+
+User query: {query}
+Skills used: {skills_used}
+Interaction process: {interaction_summary}
+Assistant result: {result}
+
+Determine if the skills used were the RIGHT choice for this task. Consider:
+1. Whether each skill's capabilities match what the task requires.
+2. Whether there is a clearly better alternative skill that should have been used instead.
+3. Whether the skill selection directly addresses the user's need.
+
+Output ONLY valid JSON with this schema:
+{{"success": true/false, "error_type": "<type or null>", "error_detail": "<reason or null>"}}
+
+A skill selection is "correct" (success=true) when the chosen skills directly address the user's need, their capabilities match what the task requires, and there isn't a clearly better alternative skill available.
+
+A skill selection is "incorrect" (success=false) when:
+- "wrong_skill": The skill doesn't match the task requirements or a different skill would have been much more appropriate.
+- "skill_error": The skill was the right choice but encountered an execution error (tool failure, exception, etc).
+- "incomplete": The skill started but did not finish the task.
+- "refusal": The skill refused to perform the task.
+- "empty": The skill returned an empty or meaningless result.
+
+For incorrect selections, provide a brief error_detail explaining why the skill choice was wrong or what went wrong.
+"""
+
+
+def _truncate(text: str, max_len: int) -> str:
+ if len(text) <= max_len:
+ return text
+ return text[:max_len - 3] + "..."
+
+
+def _format_skills(skills: list[str]) -> str:
+ if not skills:
+ return "(no skills used)"
+ return ", ".join(skills)
+
+
+def _summarize_messages(messages: list[dict], max_len: int = 3000) -> str:
+ """Extract a concise interaction summary from the message history."""
+ parts: list[str] = []
+ for msg in messages:
+ role = msg.get("role", "")
+ content = msg.get("content", "")
+
+ if role == "user":
+ text = content if isinstance(content, str) else str(content)
+ if text.strip():
+ parts.append(f"[User] {text.strip()}")
+
+ elif role == "assistant":
+ reasoning = msg.get("reasoning", "")
+ tool_call = msg.get("tool_call")
+ if reasoning:
+ parts.append(f"[Reasoning] {_truncate(reasoning.strip(), 200)}")
+ if tool_call and isinstance(tool_call, dict):
+ tc_name = tool_call.get("name", "")
+ if tc_name == "skill_tool":
+ try:
+ raw_args = tool_call.get("arguments", {})
+ args = (
+ json.loads(raw_args)
+ if isinstance(raw_args, str)
+ else raw_args
+ )
+ skill_name = args.get("skill_name", "")
+ parts.append(f"[Skill Call: {skill_name}]")
+ except (json.JSONDecodeError, TypeError):
+ parts.append(f"[Skill Call: skill_tool]")
+ else:
+ parts.append(f"[Tool Call: {tc_name}]")
+ if content and isinstance(content, str) and not tool_call:
+ if len(content) > 50:
+ parts.append(f"[Assistant] {_truncate(content.strip(), 200)}")
+
+ elif role == "tool":
+ text = content if isinstance(content, str) else str(content)
+ if text.strip():
+ parts.append(f"[Tool Result] {_truncate(text.strip(), 300)}")
+
+ summary = "\n".join(parts)
+ if len(summary) > max_len:
+ summary = _truncate(summary, max_len)
+ return summary
+
class TraceEvaluator:
"""Judge whether the skills used in each TraceRecord were correctly selected via LLM.
@@ -25,21 +134,21 @@ class TraceEvaluator:
Usage::
- processor = TraceEvaluator(llm_client=openai_client, llm_model="qwen3-32b")
+ evaluator = TraceEvaluator(llm_client=openai_client, llm_model="qwen3-32b")
records = parse_session("session_abc")
- processor.process(records)
+ evaluator.evaluate(records)
# records[0].success / .error_type / .error_detail are now filled
"""
def __init__(
- self,
- llm_client: Any | None = None,
- llm_model: str = "",
+ self,
+ llm_client: Any | None = None,
+ llm_model: str = "",
) -> None:
self._llm_model = str(llm_model or "").strip()
self._llm = llm_client if llm_client is not None else None
- def process(self, records: list[TraceRecord]) -> list[TraceRecord]:
+ def evaluate(self, records: list[TraceRecord]) -> list[TraceRecord]:
"""Judge skill correctness for each record, skip those with empty skills, return a new processed list."""
result = []
for record in records:
@@ -50,7 +159,117 @@ class TraceEvaluator:
return result
def _judge_one(self, record: TraceRecord) -> None:
- pass
+ if not self._llm or not self._llm_model:
+ self._fallback(record)
+ return
+
+ query = record.query or ""
+ result = record.result or ""
+
+ if not query:
+ record.success = False
+ record.error_type = "empty"
+ record.error_detail = "No user query found"
+ return
+
+ if not result:
+ record.success = False
+ record.error_type = "empty"
+ record.error_detail = "Skill returned empty result"
+ return
+
+ # Use enhanced prompt when messages are available
+ if record.messages:
+ prompt = _SKILL_CORRECTNESS_PROMPT_ENHANCED.format(
+ query=query,
+ skills_used=_format_skills(record.skills),
+ interaction_summary=_summarize_messages(record.messages),
+ result=result,
+ )
+ system_msg = (
+ "You evaluate whether the skills used were correctly selected for the user's task. "
+ "Output only valid JSON.")
+ else:
+ prompt = _SKILL_CORRECTNESS_PROMPT.format(query=query, result=result)
+ system_msg = (
+ "You evaluate whether the skills used were correctly selected for the user's task. "
+ "Output only valid JSON."
+ )
+ try:
+ response = self._llm.chat.completions.create(
+ model=self._llm_model,
+ messages=[
+ {"role": "system", "content": system_msg},
+ {"role": "user", "content": prompt},
+ ],
+ max_tokens=256,
+ stream=False,
+ )
+ content = response.choices[0].message.content
+ if content:
+ self._parse_judge_response(content, record)
+ else:
+ self._fallback(record)
+ except Exception as exc:
+ LOGGER.warning("TraceEvaluator: LLM call failed for trace %s: %s", record.trace_id, exc)
+ self._fallback(record)
+
+ @staticmethod
+ def _parse_judge_response(response: str, record: TraceRecord) -> None:
+ raw = response.strip()
+ if raw.startswith("```"):
+ raw = raw.split("\n", 1)[-1].rsplit("```", 1)[0].strip()
+ if raw.startswith("json"):
+ raw = raw[4:].strip()
+
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ LOGGER.warning("TraceEvaluator: failed to parse JSON for trace %s", record.trace_id)
+ TraceEvaluator._fallback(record)
+ return
+
+ success = bool(data.get("success", False))
+ record.success = success
+ if success:
+ record.error_type = None
+ record.error_detail = None
+ else:
+ record.error_type = data.get("error_type") or "error"
+ record.error_detail = data.get("error_detail") or ""
+
+ @staticmethod
+ def _fallback(record: TraceRecord) -> None:
+ """Heuristic fallback when LLM is unavailable or fails.
+
+ When we cannot evaluate skill correctness, conservatively mark
+ records with a non-empty result as correct (skill selection was
+ reasonable), and records with empty/poor results as incorrect.
+ """
+ query = record.query or ""
+ result = record.result or ""
+
+ if not query:
+ record.success = False
+ record.error_type = "empty"
+ record.error_detail = "No user query found"
+ return
+
+ if not result:
+ record.success = False
+ record.error_type = "empty"
+ record.error_detail = "Skill returned empty result"
+ return
+
+ if len(result) < len(query) * 0.3 and len(result) < 20:
+ record.success = False
+ record.error_type = "incomplete"
+ record.error_detail = "Result too short relative to query"
+ return
+
+ record.success = True
+ record.error_type = None
+ record.error_detail = None
-__all__ = ["TraceEvaluator"]
\ No newline at end of file
+__all__ = ["TraceEvaluator"]
diff --git a/jiuwenswarm/symphony/experience/trace/__init__.py b/jiuwenswarm/symphony/experience/trace/__init__.py
new file mode 100644
index 0000000000..e81a828ce9
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/trace/__init__.py
@@ -0,0 +1,11 @@
+from .parser import list_session_ids, parse_all_sessions, parse_session
+from .store import clear_store, load_all_records, parse_and_store
+
+__all__ = [
+ "list_session_ids",
+ "parse_session",
+ "parse_all_sessions",
+ "parse_and_store",
+ "load_all_records",
+ "clear_store",
+]
diff --git a/jiuwenswarm/symphony/experience/trace/store.py b/jiuwenswarm/symphony/experience/trace/store.py
new file mode 100644
index 0000000000..fc75468871
--- /dev/null
+++ b/jiuwenswarm/symphony/experience/trace/store.py
@@ -0,0 +1,127 @@
+"""Persistent store for parsed trace records.
+
+Provides helpers for persisting and loading TraceRecord objects,
+as well as a convenience function that parses only new sessions
+and stores their traces.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+
+from .parser import list_session_ids, parse_session, parse_all_sessions
+from ..models import TraceRecord
+
+LOGGER = logging.getLogger(__name__)
+
+
+def _store_dir() -> Path:
+ """Return the directory where processed traces are stored."""
+ from jiuwenswarm.common.utils import get_agent_sessions_dir
+ base = get_agent_sessions_dir()
+ store = base.parent / "trace_store"
+ store.mkdir(parents=True, exist_ok=True)
+ return store
+
+
+def _processed_index_path() -> Path:
+ """Path to the JSON file tracking which sessions have been processed."""
+ return _store_dir() / "processed_index.json"
+
+
+def _records_path() -> Path:
+ """Path to the JSONL file holding all stored TraceRecords."""
+ return _store_dir() / "records.jsonl"
+
+
+def _load_processed_index() -> set[str]:
+ """Load the set of session IDs that have already been processed."""
+ path = _processed_index_path()
+ if not path.exists():
+ return set()
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return set(data.get("processed_ids", []))
+ except Exception:
+ LOGGER.warning("Failed to read processed index, starting fresh", exc_info=True)
+ return set()
+
+
+def _save_processed_index(ids: set[str]) -> None:
+ """Save the set of processed session IDs."""
+ path = _processed_index_path()
+ data = {"processed_ids": sorted(ids)}
+ path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
+
+
+def parse_and_store() -> list[TraceRecord]:
+ """Parse only new (unprocessed) sessions and append their traces to the store.
+
+ Returns the list of newly parsed TraceRecords.
+ """
+ all_ids = set(list_session_ids())
+ already_processed = _load_processed_index()
+ new_ids = sorted(all_ids - already_processed)
+
+ if not new_ids:
+ LOGGER.info("parse_and_store: no new sessions to process")
+ return []
+
+ new_records: list[TraceRecord] = []
+ for session_id in new_ids:
+ traces = parse_session(session_id)
+ if traces:
+ new_records.extend(traces)
+
+ if new_records:
+ # Append to records.jsonl
+ records_path = _records_path()
+ with open(records_path, "a", encoding="utf-8") as f:
+ for record in new_records:
+ f.write(json.dumps(record.to_dict(), ensure_ascii=False) + "\n")
+ LOGGER.info("parse_and_store: stored %d new traces from %d sessions", len(new_records), len(new_ids))
+
+ # Update processed index
+ _save_processed_index(already_processed | set(new_ids))
+
+ return new_records
+
+
+def load_all_records() -> list[TraceRecord]:
+ """Load all stored TraceRecords from the records.jsonl file."""
+ records_path = _records_path()
+ if not records_path.exists():
+ return []
+
+ records: list[TraceRecord] = []
+ try:
+ with open(records_path, "r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ data = json.loads(line)
+ records.append(TraceRecord.from_dict(data))
+ except json.JSONDecodeError:
+ LOGGER.warning("Skipping malformed record line")
+ except Exception:
+ LOGGER.warning("Failed to load records", exc_info=True)
+
+ LOGGER.info("load_all_records: loaded %d records", len(records))
+ return records
+
+
+def clear_store() -> None:
+ """Remove all stored traces and the processed index."""
+ store = _store_dir()
+ 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")
+
+
+__all__ = ["parse_and_store", "load_all_records", "clear_store"]